美文网首页
多个物体跟着鼠标移动

多个物体跟着鼠标移动

作者: 聽說_0100 | 来源:发表于2018-10-30 15:09 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
    
                div{
                    width:20px;
                    height:20px;
                    border-radius: 20px;
                    background: red;
                    position: absolute;
                }
    
        </style>
    </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>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </body>
    <script>
    var div = document.getElementsByTagName('div');
    
    document.onmousemove = function(ev){
        var ev = ev||event;
        for(var i=div.length-1;i>=0;i--){
            if(i==0){
                div[i].style.left= getPos(ev).left +'px';
                div[i].style.top= getPos(ev).top+'px';
            }else{
                div[i].style.left= parseInt(div[i-1].offsetLeft) +'px';
                div[i].style.top= parseInt(div[i-1].offsetTop)+'px';
            }
    
        }
    };
    function getPos(ev){
        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft ||   document.body.scrollLeft;
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop ||     document.body.scrollTop;
        return {
            left:scrollLeft+ev.clientX,
            top:scrollTop + ev.clientY
        };
    }
    </script>
    </html>
    

    相关文章

      网友评论

          本文标题:多个物体跟着鼠标移动

          本文链接:https://www.haomeiwen.com/subject/izygtqtx.html