当我从 jquery 设置图像源时,如何检查图像是否已加载。我想在鼠标悬停时更改图像,并且由于图像尺寸较大,加载需要时间,因此希望在加载之前显示加载图像。
这是我的代码片段:
timer = setInterval(function() {
selector.attr('src', 'localhost/product/image1.jpg');
image1 是 436x436 并且它需要时间来加载我想在加载这个图像之前显示加载图像
请帮我...
当我从 jquery 设置图像源时,如何检查图像是否已加载。我想在鼠标悬停时更改图像,并且由于图像尺寸较大,加载需要时间,因此希望在加载之前显示加载图像。
这是我的代码片段:
timer = setInterval(function() {
selector.attr('src', 'localhost/product/image1.jpg');
image1 是 436x436 并且它需要时间来加载我想在加载这个图像之前显示加载图像
请帮我...
使用下面的代码
selector.attr('src', 'localhost/product/image1.jpg');
//show loader code here
var loadImage = new Image();
loadImage.src = selector.attr('src');
loadImage.onload = function(){
// hide loader code here
}
//show image on mouseenter event
img.addEventListener('mouseenter',function(){
this.setAttribute('src', 'localhost/product/image1.jpg');
//show loading image here
});
img.addEventListener('load',function(){
//Image loaded. So remove loading image here.
});
您可以使用以下函数来获取图像的加载回调:
$("#idOfImage").load(function() { /* image loaded */})
.error(function() { /* error in loading */ });
这是我在我的网站兄弟上所做的,它加载完美。
HTML
<a href="#" full="http://www.sample.com/wp-content/uploads/2015/01/plot3picture.jpg">
<img src="http://www.sample.com/wp-content/uploads/2015/01/plot3picture-150x150.jpg" alt="" />
</a>
JS
$( window ).bind( 'load', function(){
setTimeout( function(){
$( 'body a' ).each( function(){
$( this ).find( 'img' ).attr( 'src', $( this ).attr( 'full' ) );
});
}, 300 );
});
在页面加载时加载两个图像。将其放在页眉中
尝试这个:
if (document.images) {
img1 = new Image();
img1.src = "imgpath/image1.png";
img2 = new Image();
img2.src = "imgpath/image2.png"";
}