event.clientX和event.clientY得到的是相对于页面的坐标,当滚动条向下移动时,则出现定位不准,所以要加上滚动条的高度
无标题文档 #div1{width:100px; height:100px; background:#0F0; position:absolute;} 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';//为left赋值 oDiv.style.top=pos.y+'px';}
查看更多关于跟随鼠标移动的div框_html/css_WEB-ITnose的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did108186