简体   繁体   English

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

[英]Retrieve text value when hover over text

I searched everywhere but can't find it. 我到处搜寻,但找不到。 So I'm asking it here. 所以我在这里问。 I want to get the text when the mouse is on top (hover) of that text inside an html page. 当鼠标位于html页面内该文本的顶部(悬停)时,我想获取文本。 I tried using getClientRect, but they only give me coordinates, and not text. 我尝试使用getClientRect,但它们只给我坐标,而不给文本。 Does anybody know how to do this with javascript or html? 有人知道如何使用javascript或html吗? Thanks. 谢谢。

If you've got access to jQuery, you can use the .mouseover() event handler. 如果可以访问jQuery,则可以使用.mouseover()事件处理程序。 You can bind it to a specific DOM element and then grab the value either through val, or innerhtml. 您可以将其绑定到特定的DOM元素,然后通过val或innerhtml获取值。

It depends on what element you're trying to get the text for, but possibly what you want to do is use the mouseenter event. 这取决于您要获取文本的元素,但是可能要使用mouseenter事件。

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

EDIT: 编辑:

How to get a word under cursor using JavaScript? 如何使用JavaScript在光标下获取单词?

Create your HTML like this 像这样创建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>

Then something like this in jQuery. 然后在jQuery中类似这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM