注意:當鼠標未滾動到指定位置時,圖片顯示爲錯誤的圖片,減少服務器端的http請求。否則,顯示圖片。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖片懶加載</title>
</head>
<style>
#d1{
height: 1000px;
}
</style>
<body>
<div id="d1"></div>
<img class="lazy" alt="" src="1111.jpg" data-src="Koala.jpg" />
<br />
<img class="lazy" alt="" src="1111.jpg" data-src="Koala.jpg" />
<script src="js/jquery-1.11.3.js"></script>
<script>
$(window).scroll(function() {//窗口滾動的時候(鼠標滾輪的時候。。)
$('img').each(function() {//把以下的方法作用到每一個img標籤,可自行加限定條件
var $imgSrc = $(this).attr('data-src');//獲取每張圖片對應地址
var $imgTop = $(this).offset().top;//獲取每張圖片對應距離document頂部的高度
var scrollT = $(window).scrollTop();//獲取滾輪滾動的距離
var halfDoc = $(window).height();//獲取瀏覽器窗口可視高度
var ifElse = (scrollT+halfDoc)>=$imgTop;//如果滾動距離加上窗口可視高度大於該圖片距離document頂部的高度
var _this=this;//保存this的作用域以便於在其它作用域上使用這個作用域
if(ifElse){//如果條件成立
setTimeout(function(){$(_this).attr('src',$imgSrc);},1000);//把圖片的src地址改成data-src的值(前面已經獲取了)
}
}); //end object 'img'
}); //end object window
</script>
</body>
</html>