<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#box {
width: 500px;
height: 500px;
background: cyan;
position: absolute;
}
#mark {
width: 250px;
height: 250px;
background: yellow;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
</div>
<script>
let box = document.getElementById('box');
let mark = null;
box.onmouseenter = function () {
mark = document.createElement('div');
mark.id = 'mark';
box.appendChild(mark);
}
box.onmousemove = function(e){
let minL = 0;
let maxL = box.offsetWidth - mark.offsetWidth; // 获取mark横向所能移动的最大距离
let minT = 0;
let maxT = box.offsetHeight - mark.offsetHeight; // 获取盒子纵向所能移动的最大距离
let left = e.clientX - box.offsetLeft-125; //获取mark最新的left值
let top = e.clientY - box.offsetTop-125; // 获取mark最新的top值
if(left<=minL){
left = minL;
}
if(left>=maxL){
left = maxL;
}
if(top<=minT){
top = minT;
}
if(top>=maxT){
top = maxT;
}
mark.style.left = left + 'px';
mark.style.top = top + 'px';
}
box.onmouseleave = function(){
box.removeChild(mark);
}
</script>
</body>
</html>