![](/img/trans.png)
[英]Attemping to get a div to "follow" cursor on mousemove, but with a delay
[英]Make div follow cursor on scroll additionally to mousemove
我目前正在嘗試實現一些自定義 cursor - 一個與 cursor 一起移動的 div。 為此,我使用以下代碼:
document.addEventListener('mousemove', this.handleMouseMove);
handleMouseMove = (event) => {
const y = event.pageY;
const x = event.pageX;
const ref = document.querySelector('.follow-cursor');
ref.style.left = x + 'px';
ref.style.top = y + 'px';
};
它工作正常,但還有一個問題:滾動。 到目前為止, div 沒有在 scroll 上移動,因此沒有跟隨 cursor 上的 scroll 。 我該如何改變呢? 參考:本網站。
我不認為這就是您鏈接到的網站的方式,但它確實有效。
handleMouseMove = (event) => {
const y = event.pageY;
const x = event.pageX;
const ref = document.querySelector('.follow-cursor')
const scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
const scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
ref.style.left = x - scrollLeft + 'px';
ref.style.top = y - scrollTop + 'px';
};
如果您應用樣式position: fixed
到您的 .follow-cursor 它應該可以工作。
是的 NickSlash 的回答很好。 你可以兩個都試試。 只是在這種情況下,不要忘記在 html 中添加 id
const cursor = document.getElementById("cursor")
const moveCursor = (event) => {
const y = event.pageY
const x = event.pageX
const scrollLeft =
window.pageXOffset !== undefined
? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollLeft
onst scrollTop =
window.pageYOffset !== undefined
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollTop
cursor.style.left = x - scrollLeft + "px"
cursor.style.top = y - scrollTop + "px"`}`
document.addEventListener("mousemove", moveCursor)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.