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

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

问题描述

如果我例如有

 < p>一些长文本< / p> 

在我的HTML页面上,我怎么知道鼠标的光标是例如上面的文字'

解决方案

除了另外两个答案,你可以使用jQuery一般来说)。



这样,你不需要考虑输出你的文本。让您的JavaScript为您做。



例如

  p>每个单词都将包含在一个span中。< / p> 
< p>第二段。< / p>
Word:< span id =word>< / span>

< script type =text / javascript>
$(function(){
//在跨度
$('p')中换行单词每个(function(){
var $ this = $(this);
$ this.html($ this.text()。replace(/ \b(\w +)\b / g,< span> $ 1< / span>));
});

//绑定到每个span
$('p span')。hover(
function(){$('#word')。 ($(this).css('background-color','#ffff66')。text());},
function(){$('#word')。 (this).css('background-color','');}
);
});
< / script>

请注意,上述代码在工作时会删除段落标签中的任何html。 / p>

jsFiddle示例


If I for example have

<p> some long text </p>

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

解决方案

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

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

e.g.

<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>

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

jsFiddle example

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

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