限制跟随鼠标移动物体坐标的具体代码
时间: 2023-06-09 17:05:52 浏览: 97
以下是一个实现限制物体跟随鼠标移动的例子:
HTML:
```
<div id="box"></div>
```
CSS:
```
#box {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
}
```
JavaScript:
```
var box = document.getElementById("box");
document.addEventListener("mousemove", function(event) {
var x = event.clientX;
var y = event.clientY;
// 距离屏幕左侧的边距
var leftOffset = box.offsetLeft;
if (x < leftOffset + box.offsetWidth / 2) {
// 如果鼠标在物体左侧,使物体不超出屏幕左侧
box.style.left = 0;
} else if (x > window.innerWidth - box.offsetWidth / 2) {
// 如果鼠标在物体右侧,使物体不超出屏幕右侧
box.style.left = window.innerWidth - box.offsetWidth + "px";
} else {
box.style.left = x - box.offsetWidth / 2 + "px";
}
// 距离屏幕顶部的边距
var topOffset = box.offsetTop;
if (y < topOffset + box.offsetHeight / 2) {
// 如果鼠标在物体上方,使物体不超出屏幕上方
box.style.top = 0;
} else if (y > window.innerHeight - box.offsetHeight / 2) {
// 如果鼠标在物体下方,使物体不超出屏幕下方
box.style.top = window.innerHeight - box.offsetHeight + "px";
} else {
box.style.top = y - box.offsetHeight / 2 + "px";
}
});
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)