JS onmousemove mousemove coordinates solitaire DIV effect instance

  • 2020-03-30 00:55:13
  • OfStack

Effect:

< img border = 0 SRC = "/ / img.jbzj.com/file_images/article/201312/20131216170129919.gif" >

 

Ideas:

Use the onmousemove event, then get the coordinates of the mouse, and then pass the DIV one by one, and finally assign the coordinates of the mouse to DIV.

Code:


<head runat="server">
    <title></title>
    <style type="text/css">
        div
        {
            width: 20px;
            height: 20px;
            background: #00FFFF;
            position: absolute;
        }
    </style>
    <script type="text/javascript">
        document.onmousemove = function (ev) {
            var div = document.getElementsByTagName('div');
            var oEvent = ev || event;       //Judgment compatibility
            var pos = GetMouse(oEvent);     //After the compatibility is determined, the horizontal and vertical coordinates are obtained by using the function of mouse movement coordinates
            for (var i = div.length - 1; i > 0; i--) {      //I'm going to iterate over DIV, starting with the last one.
                div[i].style.left = div[i - 1].offsetLeft + 'px';       //Give the offsetLeft of the previous to the latter
                div[i].style.top = div[i - 1].offsetTop + 'px';     //Give the offsetTop of the previous one to the second one
            }
            div[0].style.left = pos.x + 'px';       //Give the abscissa of the mouse to the first one
            div[0].style.top = pos.y + 'px';        //Give the ordinate of the mouse to the first one
        }
        function GetMouse(ev) {     //Gets the coordinates of the mouse movement
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
            return { x: ev.clientX + scrollLeft, y: ev.clientY + scrollTop }
        }
    </script>
</head>
<body>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
</body>


Related articles: