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
时间: 2024-10-10 10:46:49