样式跟着鼠标移动而移动,当宽高不限制的时候问题解决方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js 事件event</title>
    <style>
        #div1{
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;   /*这个是关键*/
        }
    </style>
    <script>
       function getpos(ev){
              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}
       }


        //效果是样式跟着鼠标的移动而移动
        document.onmousemove=function(ev) {  //鼠标移动
            var oEvent=ev||event;
            var oDiv=document.getElementById("div1");

            var pos = getpos(oEvent);
            oDiv.style.left=pos.x+"px";
            oDiv.style.top=pos.y+"px";

        }
    </script>
</head>
<body style="height: 2000px;width: 3000px;">
    <div id="div1"></div>
</body>
</html>

 

posted @ 2018-11-03 14:35  quitpoison  阅读(215)  评论(0编辑  收藏  举报