样式跟着鼠标移动而移动,当宽高不限制的时候问题解决方法
<!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>
本文来自博客园,作者:quitpoison,转载请注明原文链接:https://www.cnblogs.com/quitpoison/p/9900714.html