【问题标题】:Cursor replacement script breaks when scrolling滚动时光标替换脚本中断
【发布时间】:2020-03-23 17:03:52
【问题描述】:

我发现了一个小光标替换脚本,它看起来很酷,并且在全屏页面上运行良好。我在我的 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);

【问题讨论】:

    标签: javascript html css wordpress


    【解决方案1】:

    因为事件不是onscroll而是scroll

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

    您将在此处找到更多信息:https://www.w3schools.com/jsref/event_onscroll.asp

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多