给鼠标添加一个光圈,并跟随鼠标移动
时间: 2023-05-25 08:04:17 浏览: 362
可以通过CSS和JavaScript来实现给鼠标添加一个光圈,并跟随鼠标移动的效果。
首先,在CSS中创建一个光圈的样式:
```css
#circle {
position: fixed;
width: 30px;
height: 30px;
border-radius: 50%;
border: 2px solid #f00;
opacity: 0.5;
pointer-events: none;
z-index: 9999;
}
```
上述样式中,`position: fixed`将光圈定位在浏览器窗口中的固定位置,`pointer-events: none`使得光圈不会拦截任何鼠标事件,`z-index: 9999`将光圈显示在页面最上层。
接着,在JavaScript中添加跟随鼠标移动的功能:
```JavaScript
document.addEventListener("mousemove", function(e) {
var circle = document.getElementById("circle");
circle.style.left = e.clientX - 15 + "px";
circle.style.top = e.clientY - 15 + "px";
});
```
上述代码中,我们使用`addEventListener`监听鼠标移动事件。当事件触发时,获取光圈元素,计算当前鼠标位置并将光圈定位到该位置。
最后,在HTML页面中添加光圈元素:
```html
<div id="circle"></div>
```
完整代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Mouse Circle</title>
<style>
#circle {
position: fixed;
width: 30px;
height: 30px;
border-radius: 50%;
border: 2px solid #f00;
opacity: 0.5;
pointer-events: none;
z-index: 9999;
}
</style>
</head>
<body>
<div id="circle"></div>
<script>
document.addEventListener("mousemove", function(e) {
var circle = document.getElementById("circle");
circle.style.left = e.clientX - 15 + "px";
circle.style.top = e.clientY - 15 + "px";
});
</script>
</body>
</html>
```