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

HTML:

 
Move_Me

第一种:

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

 

转载于:https://www.cnblogs.com/formybestlife/p/7338282.html

你可能感兴趣的:(Js实现div随鼠标移动的方法)