小广告

效果:在可视区域内随鼠标滚动,但始终在同一个位置
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        #div{
            height:500px;
            width:100px;
            background:red;
            position:absolute;
            right:50px;
            top:100px;
        }
    </style>
</head>
<body style="height:5000px;">
<div id="div"></div>
<script>
    window.onload=window.onscroll=function(){
        var oDiv=document.getElementById("div");
        var scrolltop=document.documentElement.scrollTop||document.body.scrollTop;
        //向下距离加上可视区高减去div实际高度的一半
        var t=scrolltop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2;
        moveStart(parseInt(t));


    }

    var timer=null;
    function moveStart(iTarget)
    {
        var oDiv=document.getElementById('div');
        clearInterval(timer);
        timer=setInterval(function(){
            var iSpeed=(iTarget-oDiv.offsetTop)/4;
            iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
            if(oDiv.offsetTop==iTarget)
            {
                clearInterval(timer);
            }
            else
            {
                oDiv.style.top=oDiv.offsetTop+iSpeed+'px';
            }


        },30);
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/XinYe666666/article/details/80908329
今日推荐