JS實現(xiàn)兼容性較好的隨屏滾動效果
更新時間:2015年11月09日 10:17:52 作者:企鵝
這篇文章主要介紹了JS實現(xiàn)兼容性較好的隨屏滾動效果,演示了固定位置顯示和隨屏滾動兩種效果的實現(xiàn)方法,涉及css樣式的設置與結合時間函數(shù)遞歸調用實現(xiàn)滾屏的技巧,需要的朋友可以參考下
本文實例講述了JS實現(xiàn)兼容性較好的隨屏滾動效果。分享給大家供大家參考,具體如下:
代碼中的參數(shù)解釋如下:
id 你要滾動的內容的id
l 橫坐標的位置 不寫為緊貼右邊
t 你要放在頁面的那個位置默認是貼著底邊 0是貼著頂邊
f 1表示固定 不寫或者0表示滾動。
本代碼滾動時不會出現(xiàn)抖動,隨著屏幕大小而變動
運行效果截圖如下:

在線演示地址如下:
http://demo.jb51.net/js/2015/js-scroll-follow-src-style-codes/
具體代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>隨屏滾動</title>
<style>
html,body{
padding:0;
margin:0;
}
</style>
</head>
<body>
<div id="aa" style="width:200px;height:200px;background:#c0c0c0;" >我在隨屏滾</div>
<div id="bb" style="width:200px;height:200px;background:#c0c0c0;" >我靜止不動</div>
<div style="width:100%;height:500px;background:#000"></div>
<div style="width:100%;height:500px;background:green"></div>
<div style="width:100%;height:500px;background:red"></div>
</body>
</html>
<script>
function scroll(p){
var d = document,dd = d.documentElement,db = d.body,w = window,o = d.getElementById(p.id),ie = /msie/i.test(navigator.userAgent),style;
if(o){
o.style.cssText +=";position:"+(p.f&&!ie?'fixed':'absolute')+";"+(p.l==undefined?'right:0;':'left:'+p.l+'px;')+(p.t!=undefined?'top:'+p.t+'px':'bottom:0');
if(p.f&&ie){
o.style.cssText +=';left:expression(body.scrollLeft + '+(p.l==undefined?db.clientWidth-o.offsetWidth:p.l)+' + "px");top:expression(body.scrollTop +'+(p.t==undefined?db.clientHeight-o.offsetHeight:p.t)+'+ "px" );'
db.style.cssText +=";background-image:url(about:blank);background-attachment:fixed;"
}else{
if(!p.f){
w.onresize = w.onscroll = function(){
var timer,timer1;
return function(){
if(timer)
clearTimeout(timer);
timer = setTimeout(function(){
timer1 = setInterval(function(){
var st = db.scrollTop,c;
c = st - o.offsetTop + (p.t!=undefined?p.t:(w.innerHeight||db.clientHeight)-o.offsetHeight);
if(c!=0){
o.style.top = o.offsetTop + Math.ceil(Math.abs(c)/10)*(c<0?-1:1) + 'px';
}else{
clearInterval(timer1);
}
},10)
},100)//控制滾動的頻率越大頻率越慢
}
}()
}
}
}
}
scroll({
id:'aa'
})
scroll({
id:'bb',
l:0,
t:200,
f:1
})
</script>
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
uniapp組件傳值的方法(父傳子,子傳父,對象傳值)實戰(zhàn)案例
現(xiàn)在的前端開發(fā)中基本上都是組件化開發(fā)的,下面這篇文章主要給大家介紹了關于uniapp組件傳值(父傳子,子傳父,對象傳值)的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-03-03

