我试图使一个自定义光标图像,以便它可以取代我的实际光标在某些部分。我想实现的是显示的图像时,在部分,并使它消失时,部分是左。我设法正确地显示它,而在部分,但走出去并没有隐藏它。我做错了什么?
const box = document.querySelector(".box");
const customCursor = document.createElement("img");
customCursor.style.width = "175px";
customCursor.style.height = "175px";
customCursor.style.position = "absolute";
customCursor.src = "https://picsum.photos/175";
customCursor.style.display = "none";
box.appendChild(customCursor);
box.addEventListener("mousemove", (e) => {
customCursor.style.display = "block";
customCursor.style.left = `${e.pageX - customCursor.width / 2}px`;
customCursor.style.top = `${e.pageY - customCursor.height / 2}px`;
});
box.addEventListener("mouseleave", () => {
customCursor.style.display = "none";
});
body {
font-family: sans-serif;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.box {
cursor: none;
width: 100%;
padding: 5rem;
background-color: lightblue;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<div class="box"></div>
</div>
<script src="src/index.js"></script>
</body>
</html>
也留下一个沙盒链接-https://codesandbox.io/s/javascript-forked-6v9rcm?file=/src/index.js
2条答案
按热度按时间a6b3iqyw1#
基于Ouroborus评论
您必须将
pointer-events: none
添加到imgjjhzyzn02#
可以通过更改事件侦听器来解决此问题。如果你使用mouseover和mouseout,你会有一个更好的时间。