很多网站上,都有改变滚动条的位置(即页面文档位置)有个广告栏跟随,不管去哪,广告栏总是亲切得跟着你,还有滑动的动画效果。
来po下我的代码
html:
1 <div class="advistementFllow"> 2 <div class="advContent" id="adv"></div> 3 </div>
css:
1 *{ 2 margin:0; 3 padding: 0; 4 box-sizing: border-box; 5 } 6 .advistementFllow{ 7 height: 3000px; 8 } 9 .advContent{ 10 width:100px; 11 height: 280px; 12 border: 1px solid #000; 13 position: relative; 14 top: 50px; 15 }
js代码:
1 window.addEventListener("load",function(){ 2 var adv = document.getElementById("adv"); 3 4 window.addEventListener("scroll",function(){ 5 var scrollYPos = window.pageYOffset || document.documentElement.scrollTop 6 var start = adv.offsetTop; 7 var topPos = 50; 8 var des = scrollYPos + topPos; 9 10 moveSlowly(start,des) 11 }) 12 13 }) 14 var timer = null; 15 function moveSlowly(start,des,time){ 16 clearInterval(timer); 17 18 var SpeedTime = time || 200; 19 var distance = des - start; 20 var speed = distance/SpeedTime; 21 22 var pos = start; 23 var i = 1; 24 25 timer = setInterval(function(){ 26 if(i == SpeedTime){ 27 adv.style.top = (start+distance) + "px"; 28 clearInterval(timer) 29 }else{ 30 pos = pos + speed; 31 adv.style.top = pos+"px"; 32 i++; 33 } 34 35 },1) 36 }
这个效果好像也展示不了,感兴趣的动动手试试看效果。
代码相对简单,自己写了一个缓动公式,非常笨的方法T T
以上内容,如有错误请指出,不甚感激。