JS implementation side floating floating instance code

  • 2020-03-30 00:40:14
  • OfStack


< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201311/20131129163754069.gif" >


First, load the onscroll control scroll bar. Then write the method of caching the motion, the method of buffering the motion is to first calculate the speed of DIV buffer, and take it round, and then do the motion to determine when to reach the end. Finally, its parameters are returned. This method is then called in the onscroll, and the endpoint is calculated to give the method parameters.


<head runat="server">
    <style type="text/css">
            width: 200px;
            height: 200px;
            background: #0000FF;
            position: absolute;
            right: 0;
            bottom: 0;
    <script type="text/javascript">
        window.onscroll = function () {
            var oDiv = document.getElementById('div1');
            var DivScroll = document.documentElement.scrollTop || document.body.scrollTop;      //Get moving height
            //                        oDiv.style.top = (document.documentElement.clientHeight - oDiv.offsetHeight)/2 + DivScroll + 'px';
            move(parseInt((document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + DivScroll));    //Call pass arguments, in which the argument is the end of the DIV to go. So it's going to be (visible height -DIV height) /2+ move height
        var timer = null;
        function move(end) {
            clearInterval(timer);       //First of all, turn off the setInterval if there was one before;
            timer = setInterval(function () {       
                var oDiv = document.getElementById('div1');
                var speed = (end - oDiv.offsetTop) / 5;     //Calculate the speed that DIV is going to go, and the speed that DIV is going to go is going to be equal to (endpoint -offsettop height)/scaling coefficient
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);       //To avoid decimals, round them
                if (oDiv.offsetTop == end) {        //When DIV reaches the end, turn off setInterval;
                else {
                    oDiv.style.top = oDiv.offsetTop + speed + 'px';     //Mobile div
            }, 30);
<body style="height: 1000px;">
    <div id="div1">

Related articles: