加载图像后更改文本

时间:2014-03-26 06:33:36

标签: javascript jquery image html preload

<span>No images Loaded</span>
<div id="bar5" class="mosaic-block cover3">
    <div class="mosaic-overlay"><img src="images/Seg1.png" /></div>
    <a href="#" target="_blank" class="mosaic-backdrop">
        <div class="details">
            <h4>Mounted iMac And Desk Mod With Computer Components Built In</h4>
            <p>via Desktopped</p>
        </div>
    </a>
</div>

网站加载此图片后,我想将文本更改为其他内容(例如,1 Image Loaded)。

如何确定图像是否已加载,然后更改文本

2 个答案:

答案 0 :(得分:2)

由于您的原始问题未包含任何jQuery提及,因此这是一个简单的JavaScript解决方案:

您可以为图片使用onload处理程序:

<span><span id="imagesLoaded">No</span> images Loaded</span>
<div id="bar5" class="mosaic-block cover3">
    <div class="mosaic-overlay"><img onload="imageLoaded()" src="images/Seg1.png" /></div>
    <a href="#" target="_blank" class="mosaic-backdrop">
        <div class="details">
            <h4>Mounted iMac And Desk Mod With Computer Components Built In</h4>
            <p>via Desktopped</p>
        </div>
    </a>
</div>

和javascript:

var imageCount = 0;
function imageLoaded() {
    ++imageCount;
    document.getElementById("imagesLoaded").innerHTML = imageCount;
}

使用jQuery,如果您只想在加载页面中的所有图像时收到通知,您可以使用:

$(window).load(function() {
    // code here that runs when all images are loaded
});

如果您不想更改HTML以包含onload处理程序,并且希望每次加载图像时都收到通知,则可以使用jQuery执行此操作:

$(document).ready(function() {
    var imageLoadCount = 0;

    function updateLoadCount() {
        $("#imagesLoaded").html(imageLoadCount);
    }


    $("img").each(function() {
        // check if the image is already loaded
        if (this.complete) {
            ++imageLoadCount;
        } else {
            // image not loaded yet, install an event handler to notify us when it does
            $(this).load(function() {
                ++imageLoadCount;
                updateLoadCount();
            });
        }
    });
    if (imageLoadCount) {
        updateLoadCount();
    }
});

答案 1 :(得分:0)

您可以查看: -

$("#myImg").on('load',function() {
  alert('I loaded!');
// Do your change stuff here 
}).attr('src', 'images/Seg1.png');// Assign the Src here :-

这是Javascript方法: -

    var img = document.getElementById('yourimg');

    var imageSrc = "images/Seg1.png";
    img.onload = function() {
        // Stuff to do after image load

    };
   img.src = imageSrc;