You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测点击的元素是否为伪元素及获取点击位置的cursor类型

问题原因说明

  1. 读取cursor为空的原因:e.target.style只能读取元素行内style属性中定义的样式,你代码中cursor: move和伪元素的cursor: pointer都是写在样式表中的,属于计算样式,直接读取style属性自然返回空值。
  2. 伪元素识别的难点:伪元素不属于真实DOM节点,点击事件的target始终指向其宿主元素,无法直接通过事件对象判断点击来源是否为伪元素。

解决方案

最优方案是通过坐标比对判断点击是否落在伪元素范围内,同时可以直接匹配到对应位置的cursor值,实现逻辑如下:

  1. 点击时获取当前点击的页面坐标
  2. 计算宿主元素的位置、伪元素的尺寸与偏移,得出伪元素的坐标范围
  3. 比对点击坐标是否落在伪元素范围内,分别返回对应cursor值或点击来源判断

修正后的完整JS代码

window.addEventListener('load', () => {
  const notes = document.querySelector('#textarea-notes');
  const headerDiv = document.createElement("div");
  headerDiv.id = 'div-header';
  headerDiv.innerHTML = 'Add Notes';
  notes.parentNode.insertBefore(headerDiv, notes);

  headerDiv.addEventListener('click', e => {
    // 获取宿主元素的位置信息
    const headerRect = headerDiv.getBoundingClientRect();
    // 获取宿主元素和after伪元素的计算样式
    const hostStyle = getComputedStyle(headerDiv);
    const afterStyle = getComputedStyle(headerDiv, '::after');
    // 提取伪元素尺寸与边距数值
    const afterWidth = parseFloat(afterStyle.width);
    const afterHeight = parseFloat(afterStyle.height);

    // 计算伪元素坐标范围(适配当前场景下after跟随宿主文本排列的布局)
    const afterLeft = headerRect.left + headerDiv.scrollWidth - afterWidth;
    const afterRight = afterLeft + afterWidth;
    const afterTop = headerRect.top + (headerRect.height - afterHeight) / 2;
    const afterBottom = afterTop + afterHeight;

    // 判断点击位置
    let currentCursor, isClickPseudoElement;
    if (e.clientX >= afterLeft && e.clientX <= afterRight && e.clientY >= afterTop && e.clientY <= afterBottom) {
      currentCursor = afterStyle.cursor;
      isClickPseudoElement = true;
    } else {
      currentCursor = hostStyle.cursor;
      isClickPseudoElement = false;
    }

    console.log('当前位置cursor类型:', currentCursor);
    console.log('是否点击伪元素:', isClickPseudoElement);
  });
});

适配说明

如果你的伪元素使用了绝对定位、浮动等其他布局方式,只需要对应调整伪元素坐标范围的计算逻辑即可,整体判断逻辑通用。

内容的提问来源于stack exchange,提问作者Prosy A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 21:03:01