实现小球跟随鼠标的效果
时间: 2024-03-15 13:47:57 浏览: 113
ES6与canvas实现鼠标小球跟随效果
可以使用 JavaScript 和 CSS 实现小球跟随鼠标的效果。具体实现步骤如下:
1. 在 HTML 中添加一个小球元素:
```html
<div id="ball"></div>
```
2. 在 CSS 中设置小球的样式,包括大小、颜色、圆角等:
```css
#ball {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
z-index: 9999;
}
```
3. 在 JavaScript 中添加事件监听器,监听鼠标移动事件,并获取鼠标的坐标:
```javascript
var ball = document.getElementById('ball');
document.addEventListener('mousemove', function(event) {
var x = event.clientX;
var y = event.clientY;
});
```
4. 计算小球应该距离页面左边和顶部的距离,并将其设置为小球的样式:
```javascript
var ball = document.getElementById('ball');
document.addEventListener('mousemove', function(event) {
var x = event.clientX;
var y = event.clientY;
var ballX = x - ball.offsetWidth / 2;
var ballY = y - ball.offsetHeight / 2;
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
});
```
完整的代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小球跟随鼠标</title>
<style>
#ball {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
z-index: 9999;
}
</style>
</head>
<body>
<div id="ball"></div>
<script>
var ball = document.getElementById('ball');
document.addEventListener('mousemove', function(event) {
var x = event.clientX;
var y = event.clientY;
var ballX = x - ball.offsetWidth / 2;
var ballY = y - ball.offsetHeight / 2;
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
});
</script>
</body>
</html>
```
这样,就实现了小球跟随鼠标的效果。
阅读全文