HTML代碼
寫一個div來作為滑鼠區域
div中寫一個span顯示坐標資訊
<body> <div id=""> <span></span> </div> </body>
給div和span增加樣式并定位
<style type="text/css"> div{ position: relative;/* 定位資訊 */ background-color: #398439; /* 背景顏色 */ width: 500px; /* 寬度 */ height: 500px; /* 高度 */ } span{ position: absolute;/* 絕對定位 */ color: red; /* 文字顏色 */ } </style>
添加事件
<script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementsByTagName("div")[0];//獲取當元素節點 var oSpan = oDiv.children[0]; oDiv.onmousemove = function(e){ //滑鼠移入事件 var evt = e || event; var x = evt.offsetX; var y = evt.offsetY; oSpan.innerHTML = x + ',' + y + 'px';//顯示坐標資訊 } /* 添加一個滑鼠移出事件 */ oDiv.onmouseout = function(){ oSpan.innerHTML = ""; //滑鼠移除后 坐標資訊消失 } } </script>
效果圖
當滑鼠移入的時候左上角顯示坐標,移出隱藏,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/161547.html
標籤:JavaScript
