将鼠标悬停在文本上时检索文本值

Retrieve text value when hover over text

本文关键字:文本 检索 悬停 鼠标      更新时间:2023-09-26

我到处找都找不到。所以我在这里问它。我想在鼠标悬停在html页面内的文本顶部时获取文本。我尝试使用getClientRect,但它们只给我坐标,而不给我文本。有人知道如何用javascript或html做这件事吗?谢谢

这取决于您试图获取文本的元素,但您可能想要使用mouseenter事件。

$(parentselector).on({
    'mouseenter': function(){
            alert($(this).html()); // .html() or .val() depending on the element
        }
    },
    targetselector
);

编辑:

如何使用JavaScript在光标下获取单词?

创建这样的HTML

<html>
   <head></head>
   <body>
      <span class="word">Hello</span>
      <span class="word">I</span>
      <span class="word">am</span>
      <span class="word">new</span>
   </body>
</html>

然后在jQuery中显示类似的内容。

$('body').on({
    'mouseenter': function(){
            var txt = $(this).html();
        }
    },
    'span.word'
);

如果您有权访问jQuery,则可以使用.mouseover()事件处理程序。您可以将它绑定到特定的DOM元素,然后通过val或innerhtml获取值。