伪元素添加点击事件

47 阅读1分钟

不能直接通过onClick来给伪元素添加点击事件,但是可以在js作判断,如果点击区域在伪元素范围内,则触发伪元素点击事件,否则不触发,实现如下:

export const pseudoClick = (e, beforeWidth = 50, beforeHeight = 50, onPseudoClick = () => {}, onOutsideClick = () => {}) => {
  const containerRect = e.currentTarget.getBoundingClientRect();
  const clickX = e.clientX;
  const clickY = e.clientY;

  // These values depend on your CSS for the ::before element
  // Adjust them based on the size and positioning of your ::before
  const beforeLeft = containerRect.left; 
  const beforeTop = containerRect.top;

  if (
    clickX >= beforeLeft &&
    clickX <= beforeLeft + beforeWidth &&
    clickY >= beforeTop &&
    clickY <= beforeTop + beforeHeight
  ) {
    console.log('Clicked on the ::before area!');
    // Perform actions specific to the ::before click
    onPseudoClick();
  } else {
    console.log('Clicked outside the ::before area!');
    // Perform actions for clicks on the main element or other areas
    onOutsideClick();
  }
}