javascript - 滚动时光标替换脚本中断

标签 javascript html css wordpress

我发现了一个小光标替换脚本,看起来很奇怪,并且在全屏页面上运行得非常好。我在我的 WordPress 网站上实现了它,但我意识到,当我在必须滚动的页面上时,我的光标图像不会保持附加到我的实际指针所在的位置。滚动不会将光标的位置更新为鼠标指针。

我尝试为 onscroll 添加一个事件监听器,以在滚动时更新光标的位置,但它似乎没有执行任何操作。我还尝试将光标 div 放入另一个 div 中,并将其位置设置为粘性,但这只是破坏了整个事情。

这里有两个链接,您可以在其中查看正在运行的脚本:

krauss.fr/about (在这个页面上它工作正常) krauss.fr/works (在此页面上没有)

这是我的代码

function setCurrentCursorProps() {

// Apply translation (set to actual cursor position)
cursorEl.style.transform = `translate(${currentCursorPos.x}px, ${currentCursorPos.y}px)`;

// Ensure correct rotation transition direction
while (Math.abs(lastCursorAngle - cursorAngle) > 180) {
  if (cursorAngle > lastCursorAngle) {
    cursorAngle -= 360;
  } else if (cursorAngle < lastCursorAngle) {
    cursorAngle += 360;
  }
}

// Apply rotation
cursorImageEl.style.transform = `rotate(${cursorAngle - 90}deg)`;
}

function updateCursor() {
    window.addEventListener('mousemove', event => {
    currentCursorPos = { x: event.clientX, y: event.clientY };
    });
    window.addEventListener('onscroll', event => { //this is the code I added that doesn't work
    currentCursorPos = { x: event.clientX, y: event.clientY };
    }); 

// Interval for updating cursor-position
setInterval(setCurrentCursorProps, INTERVAL_POSITION);

// Interval for updating cursor-rotation
setInterval(() => {
const delt = {
x: lastCursorPos.x - currentCursorPos.x,
y: lastCursorPos.y - currentCursorPos.y };

if (Math.abs(delt.x) < 3 && Math.abs(delt.y) < 3) return;
cursorAngle = Math.atan2(delt.y, delt.x) * 180 / Math.PI;

setCurrentCursorProps();

lastCursorPos = currentCursorPos;
lastCursorAngle = cursorAngle;
}, INTERVAL_ROTATION);
}


return {

'initialize': () => {
   cursorEl = document.querySelector('#cursor');
  cursorImageEl = document.querySelector('#cursor > img');
  updateCursor();
} };

}();

document.addEventListener('DOMContentLoaded', rotatingCursor.initialize);

最佳答案

这是因为事件不是onscroll而是scroll:

window.addEventListener('scroll', event => {
    alert("Nice scroll !")
});
div {
  height: 900px;
}
<div><div/>

您可以在这里找到更多信息:https://www.w3schools.com/jsref/event_onscroll.asp

关于javascript - 滚动时光标替换脚本中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60818224/

相关文章:

javascript - PayPal JavaScript SDK 按钮打开大约 :blank#blocked window in Django template but not in local HTML file

javascript - 将标准 Javascript 确认对话框转换为 Bootbox 确认

javascript - 在 Firefox 中调用方法 Modal ContentWindow.postMessage 的权限被拒绝

html - 单选按钮在 IE 和 Firefox 中显示有额外的轮廓

javascript - 为什么Angular js不自动更新两倍的数字?

javascript - 我可以在 sails.js Assets 目录中轻松运行 vue.js webapp 吗?

html - 什么取代了 Bootstrap 3 中的导航列表?

html - Thin Spacer CSS 在 IE 8 和 IE 7 中无法正常工作

CSS 修复下拉菜单未显示在显示器分辨率上

html - 为什么我的 DIV 不居中?