【问题标题】:Detecting mouse cursor type change over element检测鼠标光标类型更改元素
【发布时间】:2021-06-17 17:37:38
【问题描述】:

可以在没有预定义光标样式的情况下获取当前光标类型,例如当鼠标经过文本时,链接..

类似的东西:

document.addEventListener('mouseover', (e) => {
  console.log(e.'cursorType')
});

我想在 console.log 中获取光标的状态,例如:指针、文本、移动、等待...

我在 jQuery 中找到了某种解决方案,但我正在寻找纯原版 JS 中的解决方案

感谢您的回答

【问题讨论】:

标签: javascript events cursor dom-events mouseevent


【解决方案1】:

由于它可能没有被内联定义,你需要计算样式:

我用点击这里,因为它更容易演示

document.addEventListener('click', e => {
  const tgt = e.target;
  const inline = tgt.style.cursor || "Not defined"
  const computed = window.getComputedStyle(tgt)["cursor"]
  console.log("Inline: ",inline,"Computed: ",computed)
});
.help { cursor: help }
<span style="cursor:pointer">Inline Pointer</span>
<hr>
<span class="help">CSS help</span>

【讨论】:

  • 嘿,非常感谢你,我不知道 getComputedStyle(),效果很好!
【解决方案2】:

您可以像这样从 CSS 属性“光标”中获取它:

document.addEventListener('mouseover',function(e){
    var cursor = e.target.style.cursor;
    console.log(cursor);
},false);

【讨论】:

  • 仅当内联定义时
【解决方案3】:

尝试记录e.target.style.cursor。我认为这会给你鼠标悬停在 DOM 元素上的光标类型。

【讨论】:

  • 仅当使用内联样式定义时
猜你喜欢
  • 2011-07-15
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2011-02-28
  • 2018-12-01
  • 1970-01-01
相关资源
最近更新 更多