js--事件对象的理解3
实例2: 跟随鼠标的DIV--
<script> document.onmousemove=function (ev) { var oEvent=ev||event; var oDiv=document.getElementById('div1'); var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft; oDiv.style.left=oEvent.clientX+scrollLeft+'px'; oDiv.style.top=oEvent.clientY+scrollTop+'px'; //一般都要这么写,防止潜在的问题发生。oEvent.clientY+scrollTop //非谷歌浏览器情况下document.documentElement.scrollTop;谷歌浏览器情况下document.body.scrollTop; }; </script>
实例3:offsetLeft
<head> <style> #div1 {width:100px; height:100px; background:red; border:1px solid black; padding:10px; margin:20px; position:absolute; left:100px; top:100px;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.onload=function () { var oDiv=document.getElementById('div1'); alert(oDiv.offsetLeft); }; </script> </head> <body> <div id="div1"></div> </body>