【www.gdgbn.com--js教程】
图片延迟加载效果
<script>
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?"":e(parseint(c/62)))+((c=c%62)>35?string.fromcharcode(c+29):c.tostring(36))};if("0".replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return"([3-59cf-hj-mo-rt-ycg-np-rt-z]|[12]\w)"};c=1};while(c--)if(k[c])p=p.replace(new regexp("\b"+e(c)+"\b","g"),k[c]);return p}("5 $$,$$b,$$a,$$f,$$d,$$e,$$s;(3(){5 o,b,a,f,d,e,s;o=3(id){4"1q"==1y id?g.getelementbyid(id):id};o.extend=3(h,11){i(5 p q 11){h[p]=11[p]}4 h};o.deepextend=3(h,11){i(5 p q 11){5 18=11[p];9(h===18)continue;9(1y 18==="f"){h[p]=c.callee(h[p]||{},18)}j{h[p]=18}}4 h};o.wrapper=3(me,1s){5 1z=3(){me.r(12,c)};5 1a=3(){};1a.19=1s.19;1z.19=new 1a;4 1z};b=(3(k){5 b={13:/13/.x(k)&&!/1b/.x(k),1b:/1b/.x(k),1t:/webkit/.x(k)&&!/1c/.x(k),1u:/1u/.x(k),1c:/1c/.x(k)};5 1l="";i(5 i q b){9(b[i]){1l="1t"==i?"1a":i;1b}}b.1a=1l&&1d("(?:"+1l+")[\\/: ]([\\d.]+)").x(k)?1d.$1:"0";b.ie=b.13;b.1v=b.13&&1f(b.1a,10)==6;b.ie7=b.13&&1f(b.1a,10)==7;b.1w=b.13&&1f(b.1a,10)==8;4 b})(1g.navigator.useragent.tolowercase());a=3(){5 l={isarray:3(1x){4 object.19.tostring.l(1x)==="[f 1y]"},1m:3(v,t,g){9(v.1m){4 1n(g)?v.1m(t):v.1m(t,g)}j{5 m=v.1c;g=1n(g)?0:g<0?1o.1z(g)+m:1o.20(g);i(;g=m-1?m-1:g<0?1o.1z(g)+m:1o.20(g);i(;g>-1;g--){9(v[g]===t)4 g}4-1}}};3 y(f,q){9(undefined===f.1c){i(5 j q f){9(w===q(f[j],j,f))1b}}j{i(5 i=0,m=f.1c;i css教程float"]=15}j{p.h[s.1k(j)]=15}}})}};e=(3(){5 1i,1j,17=1;9(1g.2l){1i=3(r,t,y){r.2l(t,y,w)};1j=3(r,t,y){r.removeeventlistener(t,y,w)}}j{1i=3(r,t,y){9(!y.$$17)y.$$17=17++;9(!r.w)r.w={};5 x=r.w[t];9(!x){x=r.w[t]={};9(r["on"+t]){x[0]=r["on"+t]}}x[y.$$17]=y;r["on"+t]=1w};1j=3(r,t,y){9(r.w&&r.w[t]){delete r.w[t][y.$$17]}};3 1w(){5 1x=1d,c=1f();5 x=12.w[c.t];i(5 i q x){12.$$1w=x[i];9(12.$$1w(c)===w){1x=w}}4 1x}}3 1f(c){9(c)4 c;c=1g.c;c.pagex=c.clientx+d.1u(c.1n);c.pagey=c.clienty+d.1t(c.1n);c.target=c.1n;c.1o=1o;c.1p=1p;switch(c.t){2m"mouseo教程ut":c.2n=c.toelement;1b;2m"mouseover":c.2n=c.fromelement;1b};4 c};3 1o(){12.cancelbubble=1d};3 1p(){12.1x=w};4{"1i":1i,"1j":1j,"1f":1f}})();s={1k:3(s){4 s.2k(/-([a-z])/ig,3(all,2o){4 2o.touppercase()})}};9(b.1v){try{g.execcommand("backgroundimagecache",w,1d)}catch(e){}};$$=o;$$b=b;$$a=a;$$f=f;$$d=d;$$e=e;$$s=s})();",[],149,"|||function|return|var||||if|||event|||object|from|style||name|thisp|ret|node||left|elem|callback|element||type|rect|array|false|test|handler||||arguments||||document|destination|for|else|ua|call|len|top||property|in|apply||elt|right|bottom|events|handlers|each|opacity||source|this|msie|doc|value||guid|copy|prototype|version|break|length|true|slice|fixevent|defaultview|elems|addevent|removeevent||vmark|indexof|isnan|math|lastindexof|filter|fun|args|getscrolltop|getscrollleft|currentstyle|handleevent|returnvalue|typeof|ins|subclass|opera|chrome|regexp||parseint|window|sleft|stop|alpha|camelize|runtimestyle||srcelement|stoppropagation|preventdefault|string||parent|safari|firefox|ie6|ie8|obj|array|ceil|floor|foreach|push|item|method|concat|ownerdocument|documentelement|scrolltop|body|scrollleft|contains|getboundingclientrect|getcomputedstyle|null|100|float|stylefloat||rsleft|replace|addeventlistener|case|relatedtarget|letter".split("|"),0,{}))
</script>
<script>
var lazyload = function(elems, options) {
//初始化程序
this._initialize(elems, options);
//如果没有元素就退出
if ( this.isfinish() ) return;
//初始化模式设置
this._initmode();
//进行第一次触发
this.resize(true);
};
lazyload.prototype = {
//初始化程序
_initialize: function(elems, options) {
this._elems = elems;//加载元素集合
this._rect = {};//容器位置参数对象
this._range = {};//加载范围参数对象
this._loaddata = null;//加载程序
this._timer = null;//定时器
this._lock = false;//延时锁定
//静态使用属性
this._index = 0;//记录索引
this._direction = 0;//记录方向
this._lastscroll = { "left": 0, "top": 0 };//记录滚动值
this._setelems = function(){};//重置元素集合程序
var opt = this._setoptions(options);
this.delay = opt.delay;
this.threshold = opt.threshold;
this.beforeload = opt.beforeload;
this._onloaddata = opt.onloaddata;
this._container = this._initcontainer($$(this.options.container));//容器
},
//设置默认属性
_setoptions: function(options) {
this.options = {//默认值
container: window,//容器
mode: "dynamic",//模式
threshold: 0,//加载范围阈值
delay: 100,//延时时间
beforeload: function(){},//加载前执行
onloaddata: function(){}//显示加载数据
};
return $$.extend(this.options, options || {});
},
//初始化容器设置
_initcontainer: function(container) {
var doc = document,
iswindow = container == window || container == doc
|| !container.tagname || (/^(?:body|html)$/i).test( container.tagname );
if ( iswindow ) {
container = doc.compatmode == "css1compat" ? doc.documentelement : doc.body;
}
//定义执行方法
var othis = this, width = 0, height = 0;
this.load = $$f.bind( this._load, this );
this.resize = $$f.bind( this._resize, this );
this.delayload = function() { othis._delay( othis.load ); };
this.delayresize = function(){//防止重复触发bug
var clientwidth = container.clientwidth,
clientheight = container.clientheight;
if( clientwidth != width || clientheight != height ) {
width = clientwidth; height = clientheight;
othis._delay( othis.resize );
}
};
//记录绑定元素方便移除
this._binder = iswindow ? window : container;
//绑定事件
$$e.addevent( this._binder, "scroll", this.delayload );
iswindow && $$e.addevent( this._binder, "resize", this.delayresize );
//获取容器位置参数函数
this._getcontainerrect = iswindow && ( "innerheight" in window )
? function(){ return {
"left": 0, "right": window.innerwidth,
"top": 0, "bottom":window.innerheight
}}
: function(){ return othis._getrect(container); } ;
//设置获取scroll值函数
this._getscroll = iswindow
? function() { return {
"left": $$d.getscrollleft(), "top": $$d.getscrolltop()
}}
: function() { return {
"left": container.scrollleft, "top": container.scrolltop
}};
return container;
},
//初始化模式设置
_initmode: function() {
switch ( this.options.mode.tolowercase() ) {
case "vertical" ://垂直方向
this._initstatic( "vertical", "vertical" );
break;
case "horizontal" ://水平方向
this._initstatic( "horizontal", "horizontal" );
break;
case "cross" :
case "cross-vertical" ://垂直正交方向
this._initstatic( "cross", "vertical" );
break;
case "cross-horizontal" ://水平正交方向
this._initstatic( "cross", "horizontal" );
break;
case "dynamic" ://动态加载
default :
this._loaddata = this._loaddynamic;
}
},
//初始化静态加载设置
_initstatic: function(mode, direction) {
//设置模式
var isvertical = direction == "vertical";
if ( mode == "cross" ) {
this._crossdirection = $$f.bind( this._getcrossdirection, this,
isvertical ? "_verticaldirection" : "_horizontaldirection",
isvertical ? "_horizontaldirection" : "_verticaldirection" );
}
//设置元素
var pos = isvertical ? "top" : "left",
sortfunction = function( x, y ) { return x._rect[ pos ] - y._rect[ pos ]; },
getrect = function( elem ) { elem._rect = this._getrect(elem); return elem; };
this._setelems = function() {//转换数组并排序
this._elems = $$a.map( this._elems, getrect, this ).sort( sortfunction );
};
//设置加载函数
this._loaddata = $$f.bind( this._loadstatic, this,
"_" + mode + "direction",
$$f.bind( this._outofrange, this, mode, "_" + direction + "beforerange" ),
$$f.bind( this._outofrange, this, mode, "_" + direction + "afterrange" ) );
},
//延时程序
_delay: function(run) {
cleartimeout(this._timer);
if ( this.isfinish() ) return;
var othis = this, delay = this.delay;
if ( this._lock ) {//防止连续触发
this._timer = settimeout( function(){ othis._delay(run); }, delay );
} else {
this._lock = true; run();
settimeout( function(){ othis._lock = false; }, delay );
}
},
//重置范围参数并加载数据
_resize: function(change) {
if ( this.isfinish() ) return;
this._rect = this._getcontainerrect();
//位置改变的话需要重置元素位置
if ( change ) { this._setelems(); }
this._load(true);
},
//加载程序
_load: function(force) {
if ( this.isfinish() ) return;
var rect = this._rect, scroll = this._getscroll(),
left = scroll.left, top = scroll.top,
threshold = math.max( 0, this.threshold | 0 );
//记录原始加载范围参数
this._range = {
top: rect.top + top - threshold,
bottom: rect.bottom + top + threshold,
left: rect.left + left - threshold,
right: rect.right + left + threshold
}
//加载数据
this.beforeload();
this._loaddata(force);
},
//动态加载程序
_loaddynamic: function() {
this._elems = $$a.filter( this._elems, function( elem ) {
return !this._insiderange( elem );
}, this );
},
//静态加载程序
_loadstatic: function(direction, beforerange, afterrange, force) {
//获取方向
direction = this[ direction ]( force );
if ( !direction ) return;
//根据方向历遍图片对象
var elems = this._elems, i = this._index,
begin = [], middle = [], end = [];
if ( direction > 0 ) {//向后滚动
begin = elems.slice( 0, i );
for ( var len = elems.length ; i < len; i++ ) {
if ( afterrange( middle, elems[i] ) ) {
end = elems.slice( i + 1 ); break;
}
}
i = begin.length + middle.length - 1;
} else {//向前滚动
end = elems.slice( i + 1 );
for ( ; i >= 0; i-- ) {
if ( beforerange( middle, elems[i] ) ) {
begin = elems.slice( 0, i ); break;
}
}
middle.reverse();
}
this._index = math.max( 0, i );
this._elems = begin.concat( middle, end );
},
//垂直和水平滚动方向获取程序
_verticaldirection: function(force) {
return this._getdirection( force, "top" );
},
_horizontaldirection: function(force) {
return this._getdirection( force, "left" );
},
//滚动方向获取程序
_getdirection: function(force, scroll) {
var now = this._getscroll()[ scroll ], _scroll = this._lastscroll;
if ( force ) { _scroll[ scroll ] = now; this._index = 0; return 1; }
var old = _scroll[ scroll ]; _scroll[ scroll ] = now;
return now - old;
},
//cross滚动方向获取程序
_getcrossdirection: function(primary, secondary, force) {
var direction;
if ( !force ) {
direction = this[ primary ]();
secondary = this[ secondary ]();
if ( !direction && !secondary ) {//无滚动
return 0;
} else if ( !direction ) {//次方向滚动
if ( this._direction ) {
direction = -this._direction;//用上一次的相反方向
} else {
force = true;//没有记录过方向
}
} else if ( secondary && direction * this._direction >= 0 ) {
force = true;//同时滚动并且方向跟上一次滚动相同
}
}
if ( force ) {
this._lastscroll = this._getscroll(); this._index = 0; direction = 1;
}
return ( this._direction = direction );
},
//判断是否加载范围内
_insiderange: function(elem, mode) {
var range = this._range, rect = elem._rect || this._getrect(elem),
insideh = rect.right >= range.left && rect.left <= range.right,
insidev = rect.bottom >= range.top && rect.top <= range.bottom,
inside = {
"horizontal": insideh,
"vertical": insidev,
"cross": insideh && insidev
}[ mode || "cross" ];
//在加载范围内加载数据
if ( inside ) { this._onloaddata(elem); }
return inside;
},
//判断是否超过加载范围
_outofrange: function(mode, compare, middle, elem) {
if ( !this._insiderange( elem, mode ) ) {
middle.push(elem);
return this[ compare ]( elem._rect );
}
},
_horizontalbeforerange: function(rect) { return rect.right < this._range.left; },
_horizontalafterrange: function(rect) { return rect.left > this._range.right; },
_verticalbeforerange: function(rect) { return rect.bottom < this._range.top; },
_verticalafterrange: function(rect) { return rect.top > this._range.bottom; },
//获取位置参数
_getrect: function(node) {
var n = node, left = 0, top = 0;
while (n) { left += n.offsetleft; top += n.offsettop; n = n.offsetparent; };
return {
"left": left, "right": left + node.offsetwidth,
"top": top, "bottom": top + node.offsetheight
};
},
//是否完成加载
isfinish: function() {
if ( !this._elems || !this._elems.length ) {
this.dispose(); return true;
} else {
return false;
}
},
//销毁程序
dispose: function(load) {
cleartimeout(this._timer);
if ( this._elems || this._binder ) {
//加载全部元素
if ( load && this._elems ) {
$$a.foreach( this._elems, this._onloaddata, this );
}
//清除关联
$$e.removeevent( this._binder, "scroll", this.delayload );
$$e.removeevent( this._binder, "resize", this.delayresize );
this._elems = this._binder = null;
}
}
}
</script>
<script>
var imageslazyload = $$.wrapper(function(options) {
this._initialize( options );
//如果没有元素就退出
if ( this.isfinish() ) return;
//初始化模式设置
this._initmode();
//进行第一次触发
this.resize(true);
}, lazyload);
$$.extend( imageslazyload.prototype, {
//初始化程序
_initialize: function(options) {
lazyload.prototype._initialize.call(this, [], options);
//设置子类属性
var opt = this.options;
this.onload = opt.onload;
var attribute = this._attribute = opt.attribute;
//设置加载图片集合
var getsrc = opt.getsrc,
filter = $$f.bind( this._filter, this,
opt["class"],
getsrc ? function(img){ return getsrc(img); }
: function(img){ return img.getattribute( attribute ) || img.src; },
opt.holder
);
this._elems = $$a.filter(
opt.images || this._container.getelementsbytagname("img"), filter
);
//判断属性是否已经加载的方法
this._hasattribute = $$b.ie6 || $$b.ie7
? function(img){ return attribute in img; }
: function(img){ return img.hasattribute( attribute ); };
},
//设置默认属性
_setoptions: function(options) {
return lazyload.prototype._setoptions.call(this, $$.extend({//默认值
images: undefined,//图片集合
attribute: "_lazysrc",//保存原图地址的自定义属性
holder: "",//占位图
"class": "",//筛选样式
getsrc: undefined,//获取原图地址程序
onload: function(){}//加载时执行
}, $$.extend( options, {
onloaddata: this._onloaddata
})));
},
//筛选整理图片对象
_filter: function(cls, getsrc, holder, img) {
if ( cls && img.classname !== cls ) return false;//排除样式不对应的
//获取原图地址
var src = getsrc(img);
if ( !src ) return false;//排除src不存在的
if ( src == img.src ) {
//排除已经加载或不能停止加载的
if ( img.complete || $$b.chrome || $$b.safari ) return false;
img.removeattribute("src");//移除src
}
if ( holder ) { img.src = holder; }
//用自定义属性记录原图地址
img.setattribute( this._attribute, src );
return true;
},
//显示图片
_onloaddata: function(img) {
var attribute = this._attribute;
if ( this._hasattribute( img ) ) {
img.src = img.getattribute( attribute );
img.removeattribute( attribute );
this.onload( img );
}
}
});
</script>
图片延迟加载:共有图片
张,未载入 张
<script>
var row = $$("idlazy"), msg = $$("idshow"), total = $$("idtotal"), cells = [];
for (var i = 0, n = row.cells.length; i < n; cells.push(row.cells[i++]) ) {}
function lazy(){
while(row.firstchild){ row.removechild(row.firstchild); }
for (var i = 0, n = total.value | 0; i < n; i++ ) {//加上随机参数防止缓存影响效果
var img = row.appendchild(cells[0].clonenode(true)).getelementsbytagname("img")[0];
img.setattribute("_lazysrc", img.getattribute("_lazysrc") + "?" + math.random());
cells.push(cells.shift());
}
msg.innerhtml = i;
var lazy = new imageslazyload({
container: "idlazycontainer", mode: "horizontal",
holder: "/images/cnblogs_com/cloudgamer/169629/o_dot.gif",
onload: function(img) { msg.innerhtml = --i; }
});
$$("idreset").onclick = function(){ lazy.dispose(); lazy(); }
$$("idpos").onclick = function(){
with($$("idlazycontainer").style){
if( width == "300px" ){ left = 0; width = "600px"; }else{ left = width = "300px"; }
}
lazy.resize(true);
}
}
lazy();
total.onchange = lazy;
var timer;
$$("idauto").onclick = function(){
clearinterval(timer);
if( this.value == "自动播放" ){
timer = setinterval(scroll, 50);
this.value = "停止播放"
}else{
this.value = "自动播放";
}
}
function scroll(){
var container = $$("idlazycontainer"), bak = container.scrollleft;
container.scrollleft += 50;
if ( container.scrollleft == bak ) {
clearinterval(timer); $$("idauto").value = "自动播放";
}
}
</script>