【www.gdgbn.com--jquery】
jquery 模拟淘宝商城滚动条动态图片加载
主要原理:通过 setinterval 定时事件,检测滚动条的位置,再进行 ajax 请求服务端数据,加载图片到页面上。
<script type="text/网页特效">
var iheight = 0;
var itop = 0;
var clientheight = 0;
var iintervalid = null;
var itemssize = 0;
var pageno = 1; // 当前页数,默认设为第 1 页
var pagesize = 4; // 每页显示的数量getpageheight();
// 添加定时检测事件,每2秒检测一次
iintervalid = setinterval("_onscroll();", 2000);// 取得当前页面显示所占用的高度
function getpageheight() {
if(document.body.clientheight && document.documentelement.clientheight) {
clientheight = (document.body.clientheight < document.documentelement.clientheight) ? document.body.clientheight : document.documentelement.clientheight;
} else {
clientheight = (document.body.clientheight > document.documentelement.clientheight) ? document.body.clientheight : document.documentelement.clientheight;
}iheight = math.max(document.body.scrollheight,document.documentelement.scrollheight);
}// 调用ajax取服务端数据
function show() {
pageno++;$.ajax({
url: "img.php教程?p="+pageno+"&r="+math.random(),
type: "get",
datatype: "text",
timeout: 4000,
beforesend: showloadingimg,
error: showfailure,
success: showresponse
});
}function showloadingimg() {
$("#showmore").html("显示更多结果");
}function showfailure() {
$("#showmore").html(" 获取查询数据出错 ");
}// 根据ajax取出来的json数据转换成html
function showresponse(responsedata) {
var returnjson = eval("("+responsedata+")");
itemssize = returnjson.items.length;var nextpagehtml = "";
var pageoffset = (pageno-1)*pagesize + 1;
for(i=0; inextpagehtml += " ";
nextpagehtml += "- http://www.xuekaifa.com" target="_blank" title=""+ returnjson.items[i].name +"">";
nextpagehtml += "- "+ (pageoffset + i) +"http://www.xuekaifa.com" target="_blank" title=""+ returnjson.items[i].name +"">"+ returnjson.items[i].name +"";
nextpagehtml += "";
}
nextpagehtml += "";
$("#items").html($("#items").html() + nextpagehtml);// 当前页码数小于3页时继续显示更多提示框
if(pageno < 3) {
$("#showmore").html("显示更多结果");
} else {
clearinterval(iintervalid);
$("#showmore").hide();
}
}// 判断滚动条是否到达底部
function reachbottom() {
var scrolltop = 0;
if(document.documentelement && document.documentelement.scrolltop) {
scrolltop = document.documentelement.scrolltop;
} else if (document.body) {
scrolltop = document.body.scrolltop;
}
if((scrolltop > 0) && (scrolltop + clientheight == iheight)) {
return true;
} else {
return false;
}
}// 检测事件,检测滚动条是否接近或到达页面的底部区域,0.99是为了更接近底部时
function _onscroll() {
itop = document.documentelement.scrolltop + document.body.scrolltop;
getpageheight();
if(((itop+clientheight)>parseint(iheight*0.99))||reachbottom()) {
if(pageno >= 3) {
clearinterval(iintervalid);
$("#showmore").hide();
return;
}
show();
}
};
</script>
jquery 制作随着显示页面的滚动条的滚动动态加载图片,适用于图片太多的页面,在访问网页时,可以先只加载第一屏要显示的图片,当用户进行向下滚动查看页面的时候,动态去加载这些图片,好处是减少页面第一次显示的流量,加快页面第一屏显示的速度