开发者

How can I make page scrolling trigger mouseover events?

When the mouse starts hovering over an element because of scrolling (either by wheel, or开发者_运维百科 by keyboard scrolling), it does not trigger a mouseover event on the elements it is hovering (Chrome 6 on OSX). What would be an elegant way to trigger the mouseover event for the correct elements when scrolling?


Honestly, this is gonna be a pain. You'll have to

  1. determine the size and position of every element that should get a mouseover handler.
  2. add a scroll listener to the window.
  3. In the handler, get the mouse cursor position and pageOffset.
  4. Find out which element(s) the cursor is in.
  5. manually call the actual mouseover handler
  6. (Find out which elements the cursor has left, if you want some mouseout behaviour too)

You may need to re-calculate the elements' positions and sizes if they are dynamic. (move 1. beneath 3.)

While this should work fine with block-level elements, I have absolutely no idea on a solution for inline elements.


This is much more simple in the modern day web using document.elementsFromPoint:

  1. Add a scroll listener to the window.
  2. In the handler, call document.elementsFromPoint.
  3. Manually call the actual pointerover handler for those elements. Keep track of these elements.
  4. (optionally) Manually call the actual pointermove handler for those elements.
  5. Check the list of elements from the previous time around. Manually call the actual pointerleave handler for elements no longer being hovered.

Here's some psuedo-code:

let prevHoveredEls = [];

document.addEventListener("scroll", (e) => {
  let hoveredEls = document.elementsFromPoint(e.pageX, e.pageY);
  hoveredEls = hoveredEls.filter(
    (el) => el.classList.contains("elements-cared-about")
  );
  const notHoveredEls = prevHoveredEls.filter(
    (el) => !prevHoveredEls.includes(el)
  );

  hoveredEls.forEach((el) => {
    const bcr = el.getBoundingClientRect();
    el.handlePointerEnter({
      layerX: e.pageX - bcr.left,
      layerY: e.pageY - bcr.top,
    });
  });

  notHoveredEls.forEach((el) => {
    const bcr = el.getBoundingClientRect();
    el.handlePointerLeave({
      layerX: e.pageX - bcr.left,
      layerY: e.pageY - bcr.top,
    });
  });

  prevHoveredEls = hoveredEls;
});


Try some hack like myDiv.style.opacity = 1+Math.random(); on scroll ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜