Js实现div随鼠标移动的方法

HTML:

 <div id="odiv" style=" COLOR: #666; padding: 2px 8px; FONT-SIZE: 12px; MARGIN-RIGHT: 5px; position: absolute; background: #fff; display: block; border: 1px solid #666; top: 50px; left: 10px;">     Move_Me</div>

第一种:

Js:

        
document.onmousemove = function (ev) {
var odiv= document.getElementById("odiv");
            var oEvent = ev || event;
            document.onmousemove = function (ev) {
                //IE支持event,firefox不支持
                var oEvent = ev || event;

                var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                var navtop = oEvent.clientY + scrollTop;
                var navleft = oEvent.clientX + scrollLeft;
                odiv.style.top = navtop + 'px'; //Y
                odiv.style.left = navleft + 'px';//X
            };
        }
    }

 

第二种:

Js:

document.onmousemove = function () {
   var odiv= document.getElementById("odiv");
   odiv.style.top = parseInt(window.event.y - 40) + "px"; 
  odiv.style.left = parseInt(window.event.x - 20) + "px";
}

  

要注意父元素的position定位和需要移动的div的position定位关系。我这里父div没有设置position,子div设置了position:abusolute

 

posted @ 2017-08-10 11:22  Alyson.fu  阅读(2775)  评论(0编辑  收藏  举报