문제

다음 CSS 수업이 있습니다

.bg {
   background-image: url('bg.jpg');
   display: none;
}

TD 태그에 신청하고 있습니다.

내 질문은 JavaScript/JQuery로 배경 이미지가로드를 완료했다고 어떻게 알 수 있습니까?

고맙습니다.

업데이트 : 디스플레이 속성이 추가되었습니다. 나의 주요 목표이기 때문에 그것을 볼 수 있습니다.

도움이 되었습니까?

해결책

내가이 작업을 수행하는 유일한 방법은 JavaScript를 사용하여 이미지를로드 한 다음 해당 이미지를 백 그라우드로 설정하는 것입니다.

예를 들어:

var bgImg = new Image();
bgImg.onload = function(){
   myDiv.style.backgroundImage = 'url(' + bgImg.src + ')';
};
bgImg.src = imageLocation;

다른 팁

수업을 DIV에 제공하십시오 visibility:hidden 초기 페이지로드에서. 이렇게하면 클래스를 테이블 셀에 할당 할 때 이미 브라우저 캐시에 있습니다.

@Jamie Dixon- 배경 이미지로 무엇이든하고 싶다고 말하지 않았다.

$(function( )
{
    var a = new Image;
    a.onload = function( ){ /* do whatever */ };
    a.src = $( 'body' ).css( 'background-image' );
});

이 기사가 도움이 될 수 있습니다. 관련 섹션 :

// Once the document is loaded, check to see if the
// image has loaded.
$(
    function(){
        var jImg = $( "img:first" );

        // Alert the image "complete" flag using the
        // attr() method as well as the DOM property.
        alert(
            "attr(): " +
            jImg.attr( "complete" ) + "\n\n" +

            ".complete: " +
            jImg[ 0 ].complete + "\n\n" +

            "getAttribute(): " +
            jImg[ 0 ].getAttribute( "complete" )
        );
    }
);

기본적으로 백그라운드 이미지를 선택하고 체크를 수행하여로드 된 것을 확인하십시오.

또한 IMG 태그를 DIV/배경으로 간단히 바꾸는 기능을 제공하여 ONLOAD 속성과 DIV의 유연성을 모두 활용할 수 있습니다.

물론, 당신은 코드를 미세 조정하여 당신의 요구에 가장 적합한 것에 가장 적합합니다. 그러나 나의 경우, 나는 또한 내가 기대하는 것을 더 잘 제어하기 위해 너비 또는 높이가 보존되어 있는지 확인합니다.

다음과 같이 내 코드 :

<img src="imageToLoad.jpg" onload="imageLoadedTurnItAsDivBackground($(this), true, '')">

<style>
.img-to-div {
    background-size: contain;
}
</style>

<script>
// Background Image Loaded
function imageLoadedTurnItAsDivBackground(tag, preserveHeight, appendHtml) {

    // Make sure parameters are all ok
    if (!tag || !tag.length) return;
    const w = tag.width();
    const h = tag.height();

    if (!w || !h) return;

    // Preserve height or width in addition to the image ratio
    if (preserveHeight) {
        const r = h/w;
        tag.css('width', w * r);
    } 
    else {
        const r = w/h;
        tag.css('height', h * r);
    }
    const src = tag.attr('src');

    // Make the img disappear (one could animate stuff)
    tag.css('display', 'none');

    // Add the div, potentially adding extra HTML inside the div
    tag.after(`
        <div class="img-to-div" style="background-image: url(${src}); width: ${w}px; height:${h}px">${appendHtml}</div>
    `);

    // Finally remove the original img, turned useless now
    tag.remove();
}
</script>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top