如何使用JavaScript要得到光标一个字? [英] How to get a word under cursor using JavaScript?

查看:101
本文介绍了如何使用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(/\b(\w+)\b/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>

请注意,上面的code,而它的工作原理,将去掉你的段落标记内的任何HTML。

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

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

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