相信大家見過好多隨着頁面滾動,動態加載圖片等元素的網站,我也是,以前見了好多,只是沒時間去研究,今天晚上有空,百度了一下找了一個jquery插件,作者張鑫旭,效果挺好,代碼也很簡單,使用更方便,廢話不多說,貼代碼:
使用代碼:
<html><?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
<head>
<title>scrollLoadingImg by zhaozi</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.scrollLoading-min.js"></script>
<style type="text/css">
.loadingImg{background:url(loading.gif) no-repeat center;}
</style>
<script type="text/javascript">
$(function(){
$(".loadingImg").scrollLoading();
})
</script>
</head>
<body>
<img class="loadingImg" src="pixel.gif" data-url="http://www.hb114.cc/ad/img/201012272857838.gif" width="300" height="300" />
</body>
</html>
說明:.
loadingImg //給圖片加個正在加載的圖片
pixel.gif //1像素圖片
jquery.scrollLoading-min.js 原代碼
(function($) {
$.fn.scrollLoading = function(options) {
var defaults = {
attr: "data-url"
};
var params = $.extend({}, defaults, options || {});
params.cache = [];
$(this).each(function() {
var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]);
if (!url) { return; }
//重組
var data = {
obj: $(this),
tag: node,
url: url
};
params.cache.push(data);
});
//動態顯示數據
var loading = function() {
var st = $(window).scrollTop(), sth = st + $(window).height();
$.each(params.cache, function(i, data) {
var o = data.obj, tag = data.tag, url = data.url;
if (o) {
post = o.position().top; posb = post + o.height();
if ((post > st && post < sth) || (posb > st && posb < sth)) {
//在瀏覽器窗口內
if (tag === "img") {
//圖片,改變src
o.attr("src", url);
} else {
o.load(url);
}
data.obj = null;
}
}
});
return false;
};
//事件觸發
//加載完畢即執行
loading();
//滾動執行
$(window).bind("scroll", loading);
};
})(jQuery);
over
