a.ScrollTop 계산
b.스크롤 요소의 위치 지정 값 계산
c.스크롤 주기 설정
코드는 다음과 같습니다.
/*测试用的高度*/ body{ height:3000px;} div,ul,li,body{margin:0; padding:0;} /*position:absolute;用于元素的定位*/ #roll{width:50px; height:100px; background:#99CC00; position:absolute;}
<body> <div id="roll"></div> </body>
var roll=document.getElementById('roll'), initX=0, initY, compY, sp=15, //可调整时间间隔,步进值不宜过大,不然IE下有点闪屏; timeGap=5, doc=document.documentElement, docBody=document.body; compY=initY=200; roll.style.right=initX+"px"; ;(function(){ var curScrollTop=(doc.scrollTop||docBody.scrollTop||0)-(doc.clientTop||docBody.clientTop||0); //每次comP的值都不一样;直到roll.style.top===doc.scrollTop+initY; compY+=(curScrollTop+initY-compY)/sp; roll.style.top=Math.ceil(compY)+"px"; setTimeout(arguments.callee,timeGap); })();