<h1>
X 轴的坐标位置是 : <span class="x">0</span> <br>
Y 轴的坐标位置是 : <span class="y">0</span>
</h1>
<script>
// 获取元素
var x = document.querySelector('.x')
var y = document.querySelector('.y')
// 添加事件
document.onmousemove = function (e) {
// 事件对象兼容
e = e || window.event
// 获取坐标点
var x1 = e.clientX
var y1 = e.clientY
// 修改span的文本内容
x.innerText = x1
y.innerText = y1
}
</script>
二、局部获取坐标点(比如Y轴局部)
<p>x轴坐标是:<span class="x">0</span></p>
<p>y轴坐标是:<span class="y">0</span></p>
<script>
var pbox = document.querySelectorAll('p')
var xbox = document.getElementsByClassName('x')[0]
var ybox = document.getElementsByClassName('y')[0]
// 可以获得局部坐标点
pbox.forEach(function(item){
// console.log(item);
item.addEventListener('mousemove',fn)
})
function fn(e){
e = e || window.event
var x = e.clientX
var y = e.clientY
xbox.innerText = x
ybox.innerText = y
}
</script>