當頁面有大量圖片時, 透過隨scroll bar移動位置才載入圖片, 可減少頁面延遲, 並提升使用者瀏覽體驗的效果.
本文採用jquery操作, 以簡單方式呈現.
1.取得scroll bar位置
var scrollVal = $(this).scrollTop();
2.取得windown高度
$(window).height()
3.取得每個元件的位置
$("img").each(function (index) {
$(this).offset().top;)
};
當元件位置小於 scroll bar位置+windown高度, 就會觸發image顯示,利用改變image的src地址載入圖片.
[ 完整程式碼 ]
$(function () {
$(window).scroll(function () {
var scrollVal = $(this).scrollTop();
//$(".qScrollTop").text(scrollVal);
$("img").each(function (index) {
if ($(this).offset().top < (scrollVal + $(window).height())) {
if ($(this).attr("src") == "#") {
$(this).attr("src", $(this).attr("alt"));
//$(this).animate({ left: '250px', opacity: '1' }); 動畫效果 opacity一開始要先設0
}
}
});
});
//初次載入先顯示window內可見的圖片
$(window).one("load", function () {
$("img").each(function (index) {
if ($(this).offset().top < ($(window).height())) {
$(this).attr("src", $(this).attr("alt"));
//$(this).animate({ left: '250px', opacity: '1' }); 動畫效果 opacity一開始要先設0
}
});
});
});
<tr><td>01<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>02<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>03<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>04<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>05<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>06<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>07<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>08<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>09<img alt="images/010.jpg" src="#" height="200" /></td></tr>
<tr><td>10<img alt="images/010.jpg" src="#" height="200" /></td></tr>
</table>
留言列表