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

查看:28
本文介绍了如何使用 JavaScript 获取光标下的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

<p> some long text </p>

在我的 HTML 页面上,我如何知道鼠标光标位于单词文本"上方?

on my HTML page, how can I know that cursor of mouse is for example above the word 'text'?

推荐答案

除了其他两个答案之外,您还可以使用 jQuery(或通常的 javascript)将段落拆分为跨度.

Further to the two other answers, you may be able to split your paragraphs up into spans using jQuery (or javascript generally).

这样,您就无需考虑在单词周围输出带有跨度的文本.让您的 javascript 为您完成.

That way, you wouldn't need to think about outputting your text with spans around the words. Let your javascript do it for you.

例如

<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>
Word: <span id="word"></span>

<script type="text/javascript">
    $(function() {
        // wrap words in spans
        $('p').each(function() {
            var $this = $(this);
            $this.html($this.text().replace(/(w+)/g, "<span>$1</span>"));
        });

        // bind to each span
        $('p span').hover(
            function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
            function() { $('#word').text(''); $(this).css('background-color',''); }
        );
    });
</script>

请注意,上面的代码虽然有效,但会删除段落标签内的所有 html.

Note that the above code, while it works, will strip out any html inside your paragraph tags.

jsFiddle 示例

这篇关于如何使用 JavaScript 获取光标下的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆