覆盖光标位置



我想要一个函数,当我将鼠标悬停在导航栏上时,它会覆盖 e.clientY 和 e.clientX,以便光标位于背景圆圈的中间。有人可以帮忙吗?

const cursor = document.querySelector('#cursor');
document.addEventListener("mousemove", function(e) {
cursor.setAttribute("style", "top: " + (e.clientY - 10) + "px; left: " + (e.clientX - 10) + "px;")
})
document.getElementById("navbarimg").addEventListener("mouseover",function(e) {
cursor.classList.toggle("hover")
})
document.getElementById("navbarimg").addEventListener("mouseout",function(e) {
cursor.classList.toggle("hover")
})
body{margin:0;height:100vh;background:rgb(27,27,27);}
#cursor{width:30px;height:30px;border:2px solid gray;border-radius:50%;position:fixed;transition-duration: 100ms;transition-timing-function: ease-out;}
#navbarimg{position:absolute;top:50%;left:50%;transform:tranlate(-50%,-50%);}
#cursor.hover{width:100px;height:100px;opacity:0.1;background-color:gray;}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cursor</title>
</head>
<body>
<div id="cursor"></div>
<div class="nav">
<a href="../"><img id="navbarimg"  src="navbar.svg" alt="navbar"></a>           </div>
</body>

只需将transform: translate(-50%, -50%);添加到光标中,无需任何偏移

const cursor = document.querySelector('#cursor');
document.addEventListener("mousemove", function(e) {
cursor.setAttribute("style", "top: " + (e.clientY) + "px; left: " + (e.clientX ) + "px;")
})
document.getElementById("navbarimg").addEventListener("mouseover", function(e) {
cursor.classList.toggle("hover")
})
document.getElementById("navbarimg").addEventListener("mouseout", function(e) {
cursor.classList.toggle("hover")
})
body {
margin: 0;
height: 100vh;
background: rgb(27, 27, 27);
}
#cursor {
width: 30px;
height: 30px;
border: 2px solid gray;
border-radius: 50%;
position: fixed;
transform: translate(-50%, -50%);
transition-duration: 100ms;
transition-timing-function: ease-out;
}
#navbarimg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#cursor.hover {
width: 100px;
height: 100px;
opacity: 0.1;
background-color: gray;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewpoint" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cursor</title>
</head>
<body>
<div id="cursor"></div>
<div class="nav">
<a href="../"><img id="navbarimg" src="navbar.svg" alt="navbar"></a>
</div>
</body>

最新更新