美文网首页
js事件2 跟着鼠标走的div

js事件2 跟着鼠标走的div

作者: maomizone | 来源:发表于2017-03-20 22:31 被阅读0次

    获得的是鼠标可视区的鼠标坐标

    myEvent.clientX / myEvent.clientY

    获取页面的水平滚动条位置

    document.documentElement.scrollLeft || document.body.scrollLeft

    获取页面的数值滚动条位置

    document.documentElement.scrollTop || document.body.scrollTop

    示意图

    div.style.top = clientY + scrollTop

    shiyitu.png
    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>跟着鼠标走的div</title>
        <script>
    
            function getPos(ev){
                var myEvent = ev || event;
                var x = myEvent.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
                var y = myEvent.clientY + (document.documentElement.scrollTop || document.body.scrollTop);
                return {x:x , y:y};
            }
            window.onload = function(){
                document.onmousemove = function(ev){
                    var div = document.getElementsByTagName("div")[0];
                    div.style.left =getPos(ev).x + "px";
                    div.style.top =getPos(ev).y + "px";
                }
            }
        </script>
    </head>
    <body style="height:5000px;">
    <div style="width: 100px;height:100px;background-color: red;position: absolute"></div>
    </body>
    </html>
    
    

    效果

    eventSport.gif

    相关文章

      网友评论

          本文标题:js事件2 跟着鼠标走的div

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