在性能方面考虑了由于连续触发onscroll事件,频繁调用回调函数而产生的性能问题。可以将回调函数缓存一段时候后执行,即当这段时间内多次触发了onscroll事件,但回调函数只会执行一次。
结合淡入/淡出/减速运动效果实现的返回顶部功能
返回顶部
<script> <br>var tool = { <br>//此方法为了避免在 ms 段时间内,多次执行func。常用 resize、scoll、mousemove等连续性事件中 <br>buffer: function(func, ms, context){ <br>var buffer; <br>return function(){ <br>if(buffer) return; <br>buffer = setTimeout(function(){ <br>func.call(this) <br>buffer = undefined; <br>},ms); <br>}; <br>}, <br>/*读取或设置元素的透明度*/ <br>opacity: function(elem, val){ <br>var setting = arguments.length > 1; <br>if("opacity" in elem.style){//elem.style["opacity"] 读取不到CSS class中的值 <br>return setting ? elem.style["opacity"] = val : elem.style["opacity"]; <br>}else{ <br>if(elem.filters && elem.filters.alpha) { <br>return setting ? elem.filters.alpha["opacity"] = val*100 : elem.filters.alpha["opacity"]/100; <br>} <br>} <br>}, <br>//获取或设置文档对象的scrollTop <br>//function([val]) <br>documentScrollTop: function(val){ <br>var elem = document; <br>return (val!== undefined) ? <br>elem.documentElement.scrollTop = elem.body.scrollTop = val : <br>Math.max(elem.documentElement.scrollTop, elem.body.scrollTop); <br>} <br>}; <br>//动画效果 <br>var effect = { <br>//淡入 <br>fadein: function (elem){ <br>var val = 0; <br>var interval = 25; <br>setTimeout(function(){ <br>val = 0.1; <br>if(val>1){ <br>tool.opacity(elem, 1) <br>return; <br>}else { <br>tool.opacity(elem, val) <br>setTimeout(arguments.callee, interval); <br>} <br>},interval); <br>}, <br>//淡出 <br>fadeout: function (elem){ <br>var val = 1; <br>var interval = 25; <br>setTimeout(function(){ <br>val -= 0.1; <br>if(val < 0){ <BR>tool.opacity(elem, 0) <BR>return; <BR>}else { <BR>tool.opacity(elem,val) ; <BR>setTimeout(arguments.callee, interval); <BR>} <BR>},interval); <BR>}, <BR>//减速移动滚动条 <BR>move: function(scrollTop){ <BR>setTimeout(function(){ <BR>scrollTop = Math.floor((scrollTop * 0.65)); <BR>tool.documentScrollTop(scrollTop); <BR>if(scrollTop !=0 ){ <BR>setTimeout(arguments.callee, 25); <BR>} <BR>},25); <BR>} <BR>}; <BR>//主程序 <BR>(function(){//gotop <BR>var visible = false; <BR>var elem = document.getElementById("gotop"); <BR>function onscroll(){ <BR>var scrollTop = tool.documentScrollTop(); <BR>if(scrollTop > 0){ <br>if(!visible){ <br>effect.fadein(elem) <br>visible = true; <br>} <br>}else{ <br>if(visible){ <br>effect.fadeout(elem); <br>visible = false; <br>} <br>} <br>} <br>function onclick(){ <br>var scrollTop = tool.documentScrollTop(); <br>effect.move(scrollTop); <br>} <br>elem.onclick = onclick; <br>window.onscroll = tool.buffer(onscroll, 200, this); <br>})(); <br></script>
placeholder