提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
使用html 制作简单的元素跟随鼠标移动。
一、原理
首先需要监听鼠标移动事件,我使用的是 addEventListener。然后将获取的鼠标位置赋予需要移动的元素。此元素需要将position设为absolute,若想鼠标处于元素中心则需要减去一半的宽度和高度,与居中的原理相似。
二、获取到的元素位置
clientX, clientY是鼠标当前相对于网页的位置。
offsetX, offsetY是鼠标当前相对于某一元素的位置。
screenX, screenY是相对于用户显示器的位置。
x,y是鼠标当前相对于当前浏览器的位置。
其中client,screen,x都不会跟随滑动栏超出增加,而offset则会随着滑动栏超出增加
三、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
width: 100%;
height: 5000px;
}
.dot {
width: 100px;
height: 100px;
background-color: red;
transition: transform 2s;
position: absolute;
top: 0;
left: 0;
}
.dot:hover {
transform: rotateZ(180deg);
}
.box {
width: 100%;
height: 100%;
background: grey;
}
</style>
</head>
<body>
<div class="box">
<div class="dot"></div>
</div>
</body>
<script>
const box = document.querySelector('.box');
const dot = document.querySelector('.dot');
console.log(box);
box.addEventListener('mousemove', (e) => {
console.log(e);
dot.style.top = e.y - 50 + 'px';
dot.style.left = e.x - 50 + 'px';
});
</script>
</html>