用js写一个跟随鼠标移动的点
时间: 2024-02-21 19:00:01 浏览: 19
好的,以下是实现跟随鼠标移动的点的JS代码:
```javascript
// 创建一个div元素作为点
var dot = document.createElement('div');
dot.style.width = '10px';
dot.style.height = '10px';
dot.style.borderRadius = '50%';
dot.style.backgroundColor = 'red';
dot.style.position = 'absolute';
document.body.appendChild(dot);
// 监听鼠标移动事件
document.addEventListener('mousemove', function(e) {
// 获取鼠标当前位置
var x = e.clientX;
var y = e.clientY;
// 将点的位置设置为鼠标位置
dot.style.left = x + 'px';
dot.style.top = y + 'px';
});
```
解释一下上面的代码:
首先我们创建了一个div元素,作为我们的点,并设置了点的样式。然后我们监听了整个文档的`mousemove`事件,当鼠标移动时,获取鼠标的位置,并将点的位置设置为鼠标的位置。最后,我们将点添加到了`body`元素中。
这样就实现了一个简单的跟随鼠标移动的点。
相关问题
用js写跟随鼠标移动
可以使用 JavaScript 在网页中跟随鼠标移动。下面是一个例子:
```
<html>
<head>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
document.addEventListener("mousemove", function(event) {
var x = event.clientX;
var y = event.clientY;
document.getElementById("box").style.top = y + "px";
document.getElementById("box").style.left = x + "px";
});
</script>
</body>
</html>
```
这段代码会在页面中创建一个红色的正方形,并使它跟随鼠标的移动而移动。
希望这对你有帮助!
html完成一个跟随鼠标移动的层
以下是一个使用HTML和JavaScript实现鼠标移动跟随效果的简单代码案例:
```html
<!DOCTYPE html>
<html>
<head>
<title>跟随鼠标移动的层</title>
<style type="text/css">
#follower {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="follower"></div>
<script type="text/javascript">
document.onmousemove = function(event) {
var mouseX = event.clientX; // 获取鼠标的水平位置
var mouseY = event.clientY; // 获取鼠标的垂直位置
var follower = document.getElementById('follower');
// 将<div>元素的位置设置为鼠标的位置
follower.style.left = mouseX + 'px';
follower.style.top = mouseY + 'px';
};
</script>
</body>
</html>
```