2、实现示例大概功能:文字根据鼠标所在位置,往相反的方向移动,如鼠标在上,文字则向下;鼠标在右,文字则向左。具体效果查看实际示例。
时间: 2024-03-16 14:45:42 浏览: 21
这个功能可以通过在页面上监听鼠标移动事件,然后根据鼠标所在位置来调整文字所在的位置。具体实现步骤如下:
1. 在HTML中创建一个文本元素,设置其初始位置为页面中心。
```html
<div id="text" style="position: absolute; top: 50%; left: 50%;">Hello world!</div>
```
2. 使用JavaScript监听鼠标移动事件,并获取鼠标相对于页面左上角的坐标。
```javascript
var text = document.getElementById('text');
document.onmousemove = function(e) {
var x = e.pageX;
var y = e.pageY;
// 根据鼠标位置调整文本位置
}
```
3. 根据鼠标位置和文本位置的差值,计算出文本应该移动的距离。
```javascript
var rect = text.getBoundingClientRect();
var dx = x - (rect.left + rect.right) / 2; // 鼠标与文本中心点的水平距离
var dy = y - (rect.top + rect.bottom) / 2; // 鼠标与文本中心点的垂直距离
var tx = rect.left - dx; // 文本应该移动到的水平坐标
var ty = rect.top - dy; // 文本应该移动到的垂直坐标
```
4. 根据文本应该移动到的坐标,设置文本的位置。
```javascript
text.style.left = tx + 'px';
text.style.top = ty + 'px';
```
5. 最后,为了让文本始终在页面内部移动,需要对文本的位置做一些限制。
```javascript
var maxWidth = window.innerWidth - rect.width; // 页面最大水平坐标
var maxHeight = window.innerHeight - rect.height; // 页面最大垂直坐标
tx = Math.max(0, Math.min(maxWidth, tx)); // 限制水平坐标在页面内部
ty = Math.max(0, Math.min(maxHeight, ty)); // 限制垂直坐标在页面内部
text.style.left = tx + 'px';
text.style.top = ty + 'px';
```
完整代码如下:
```html
<div id="text" style="position: absolute; top: 50%; left: 50%;">Hello world!</div>
<script>
var text = document.getElementById('text');
document.onmousemove = function(e) {
var x = e.pageX;
var y = e.pageY;
var rect = text.getBoundingClientRect();
var dx = x - (rect.left + rect.right) / 2;
var dy = y - (rect.top + rect.bottom) / 2;
var tx = rect.left - dx;
var ty = rect.top - dy;
var maxWidth = window.innerWidth - rect.width;
var maxHeight = window.innerHeight - rect.height;
tx = Math.max(0, Math.min(maxWidth, tx));
ty = Math.max(0, Math.min(maxHeight, ty));
text.style.left = tx + 'px';
text.style.top = ty + 'px';
}
</script>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)