欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JS实现侧悬浮浮动实例代码

时间:2021-04-04 10:16:27|栏目:JavaScript代码|点击:

效果:

思路:

首先,加载onscroll控制滚动条。然后写缓存运动的方法,缓冲运动的方法是先计算出DIV缓冲的速度,并且将其取整,再进行运动判断什么时候到达终点。最后将其参数返回。再在onscroll里面调用此方法,并且将终点计算出来赋予此方法的参数。

代码:

复制代码 代码如下:

<head runat="server">
    <title></title>
    <style type="text/css">
        #div1
        {
            width: 200px;
            height: 200px;
            background: #0000FF;
            position: absolute;
            right: 0;
            bottom: 0;
        }
    </style>
    <script type="text/javascript">
        window.onscroll = function () {
            var oDiv = document.getElementById('div1');
            var DivScroll = document.documentElement.scrollTop || document.body.scrollTop;      //获取移动高度
            //                        oDiv.style.top = (document.documentElement.clientHeight - oDiv.offsetHeight)/2 + DivScroll + 'px';
            move(parseInt((document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + DivScroll));    //调用传参,其中里面的参数是DIV要走的终点。也就是(可视高度-DIV高度)/2+移动高度
        };

        var timer = null;
        function move(end) {
            clearInterval(timer);       //首先,先关闭之前如果有开启的setInterval;
            timer = setInterval(function () {      
                var oDiv = document.getElementById('div1');
                var speed = (end - oDiv.offsetTop) / 5;     //计算DIV要走的速度,DIV要走的速度就等于(终点-offsetTop高度)/缩放系数
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);       //为了避免小数,将其取整
                if (oDiv.offsetTop == end) {        //当DIV到达终点,则关闭setInterval;
                    clearInterval(timer);
                }
                else {
                    oDiv.style.top = oDiv.offsetTop + speed + 'px';     //移动div
                }
            }, 30);
        }
    </script>
</head>
<body style="height: 1000px;">
    <div id="div1">
    </div>
</body>

上一篇:微信小程序实现留言板(Storage)

栏    目:JavaScript代码

下一篇:easyUI实现(alert)提示框自动关闭的实例代码

本文标题:JS实现侧悬浮浮动实例代码

本文地址:http://www.codeinn.net/misctech/94569.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有