提问人:Muhammad Abdullah 提问时间:11/3/2023 最后编辑:Professor AbronsiusMuhammad Abdullah 更新时间:11/3/2023 访问量:34
自定义光标滚动,除非移动鼠标 HTML、CSS、JS
Custom Cursor scrolls away unless mouse is moved HTML CSS JS
问:
我正在为我的网站进行自定义光标设计。我找到了一个我喜欢的设计,并根据自己的喜好对其进行了调整。唯一的问题是,当我滚动时,设计也会滚动。当我移动鼠标时,它会返回。
const cursor = document.querySelector('.cursor')
document.addEventListener('mousemove', (e) => {
cursor.setAttribute("style", "top: " + (e.pageY - 60) + "px; left: " + (e.pageX - 60) + "px;")
})
document.addEventListener("click", (e) => {
console.log(e.target)
cursor.classList.add('click')
setTimeout(() => {
cursor.classList.remove('click')
}, 500)
})
@import url("https://fonts.googleapis.com/css?family=Montserrat:400,400i,700");
body {
font-family: Montserrat, sans-serif;
font-size: 30px;
background: #000;
color: #fff;
cursor: none;
position: relative;
min-height: 100vh;
padding: 0px;
margin: 0px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
div {
display: inline-block;
padding: 20px;
}
.cursor {
pointer-events: none;
position: absolute;
width: 80px;
height: 80px;
background: #fff;
border-radius: 50%;
mix-blend-mode: exclusion;
background: radial-gradient(circle, #000 0%, #000 3.99%, #fff 4%, #fff 100%);
}
.cursor.click {
animation: click .3s ease-in-out;
}
@keyframes click {
0% {
transform: scale(1);
}
5% {
transform: scale(1.3);
}
100% {
transform: scale(1);
}
}
<div class="cursor">
</div>
<h1>Hello world</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mi nisi, congue at mattis in, fermentum at purus. In venenatis diam eget facilisis pharetra. Nam eget metus gravida nibh consectetur auctor. Nunc dignissim eros nunc, at tempus dui tincidunt quis.
Mauris augue dui, pretium vel nunc ac, lacinia condimentum est. Maecenas mattis ligula non mi rutrum sodales. Aenean porta augue eget ex convallis, eget pulvinar felis accumsan. Suspendisse lorem nunc, dignissim at sapien eget, condimentum varius enim.
Duis bibendum sed justo non laoreet. Ut egestas nisi vel interdum viverra. Ut consectetur ex sed sem pretium, convallis egestas tellus elementum. Maecenas libero felis, efficitur nec dolor et, ultrices dignissim magna.</p>
<br>
我尝试将 pageX 和 pageY 更改为 clientX 和 clientY,但它所做的只是使光标在滚动太远时无法恢复。
答:
0赞
Unlucky
11/3/2023
#1
在 css 中更改为 forposition: absolute
position: fixed
.cursor
这将确保光标相对于视口,而不是最近的相对定位祖先(滚动不会影响视口,但可能会影响 HTML 元素,因此滚动时光标(带有 )应保持在原位)position: fixed
而且,您还需要在 JS 中更改 and(因为不受滚动的影响,并且确实如此)pageY
pageX
clientX
clientY
client
page
评论