<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
#areaDiv{
width: 300px;
height: 100px;
border: solid 1px black;
}
#showMsg{
width: 100px;
height: 20px;
border: solid 1px black;
}
#box1{
width: 100px;
height: 100px;
background-color: red;
/*
* 要设置偏移量left,top,要开启绝对定位
*/
position: absolute;
}
</style>
<body>
<div id="areaDiv"></div>
<br />
<div id="showMsg"></div>
<div id="box1">
</div>
</body>
<script type="text/javascript">
/*当鼠标移动在areaDiv中,showMsg中显示鼠标坐标
*/
var areaDiv=document.getElementById("areaDiv");
var showMsg=document.getElementById("showMsg");
//鼠标移动事件
areaDiv.onmousemove=function(event){
// alert("hello");
//Event事件对象作为实参传入响应函数
var x=event.clientX;
var y=event.clientY;
showMsg.innerHTML="x="+x+","+"y="+y;
}
// https://www.w3cschool.cn/jsref/dom-obj-event.html
//#box1跟随鼠标移动
var box1=document.getElementById("box1");
document.onmousemove=function(event){
//解决兼容性问题
event=event||window.event;
//css设置偏移量,坐标设置
//clientX是相对可见窗口的坐标,有滚动条的时候雨div相对页面的坐标不对应,此时要有pagex
box1.style.left=event.pageX+"px";
box1.style.top=event.pageY+"px";
}
</script>
</html>