一、文檔中的鼠標移動事件------onmousemove
<script> document.onmousemove=function(){ console.log(arguments.length); console.log(arguments[0]); //有一個參數e,是一個對象,是事件參數對象 } </script>
二、clientX和clientY獲取橫縱坐標----案例圖片隨着鼠標移動
<img src="1.png" alt="" id="im" style="position: absolute;left: 0;top: 0;"> <script> document.onmousemove=function(e){ //谷歌和火狐中有這個對象e //IE8中沒有這個是對象e,而是用window.event e=window.event||e; document.getElementById("im").style.left=e.clientX+"px"; document.getElementById("im").style.top=e.clientY+"px"; } </script>
三、pageX和pageY獲取橫縱坐標-----案例圖片隨着鼠標移動
<img src="1.png" alt="" id="im" style="position: absolute;left: 0;top: 0;"> <script> document.onmousemove=function(e){ //如果有滾動條的時候,拉動滾動條,會出現bug //解決辦法是用pageX和pageY代替 //但是這兩個屬性火狐和谷歌可以用,IE9中不支持 e=window.event||e; document.getElementById("im").style.left=e.pageX+"px"; document.getElementById("im").style.top=e.pageY+"px"; } </script>
四、兼容性寫法(封裝對象)
<!-- 封裝關於獲取橫縱坐標的兼容性代碼,並且把代碼放在一個對象中 --> <script> var evt={ //window.event和事件參數e的兼容 getEvent:function(evt){ return window.event||evt; }, //可視區域的橫坐標的兼容代碼 getClientX:function(evt){ return this.getEvent(evt).clientX; }, //可視區域的縱坐標的兼容代碼 getClientY:function(evt){ return this.getEvent(evt).clientY; }, //頁面向左卷曲出去的橫坐標 getScrollLeft:function(){ return window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft||0; }, //頁面向上卷曲出去的橫坐標 getScrollTop:function(){ return window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop||0; }, //相對於頁面(屏幕)的橫坐標(pageX或者是clientX+scrollLeft) getPageX:function(evt){ return this.getEvent(evt).pageX?this.getEvent(evt).pageX:this.getClientX(evt)+this.getScrollLeft(); }, //相對於頁面(屏幕)的縱坐標(pageY或者是clientY+scrollTop) getPageY:function(evt){ return this.getEvent(evt).pageY?this.getEvent(evt).pageY:this.getClientY(evt)+this.getScrollTop(); } } </script>