1. 程式人生 > >前端開發之js基礎(11)

前端開發之js基礎(11)

實現網站跟隨小廣告

css程式碼

 <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            #box{
                width: 100%;
                height: 2500px;
                border: 1px solid #FF0000;
                position: relative;

            }
            #box
#left{ position: absolute; left: 20px; top: 50px; } #box #right{ position: absolute; right: 20px; top: 50px; }
</style>

html程式碼

<body>
        <div
id="box">
<div id="left"><img src="../images/topimg/aside.jpg"/></div> <div id="right"><img src="../images/topimg/aside.jpg"/></div> <div id="content"> </div> </div> </body>

js程式碼

<script
type="text/javascript">
//封裝動畫 function animate(obj,target){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var speed = (target-obj.offsetTop)/10; speed = speed>0?Math.ceil(speed):Math.floor(speed); obj.style.top = obj.offsetTop+speed+"px"; var result = target-obj.offsetTop; if(Math.abs(result)<Math.abs(speed)){ clearInterval(obj.timer); obj.style.top = target+"px"; } },30); } //封裝滾動 function scroll(){ if(window.pageYOffset!=null){ return { top:window.pageYOffset } } } //事件 window.onload = function(){ var box = document.getElementById("box"); var left = box.children[0]; var right = box.children[1]; window.onscroll = function(){ var top = scroll().top; animate(left,top+80); animate(right,top+80); } } </script>