悬停时突出显示文本块中的单个单词

时间:2011-07-28 21:10:23

标签: javascript jquery css

在javascript / jQuery中,有没有办法识别文本块/段落中的单词?例如,假设我有以下段落:

  

Lorem ipsum dolor坐下来,精神上的精神。 Mauris suscipit interdum fermentum。 Aenean fermentum imperdiet augue,et venenatis lectus semper vel。在quam egestas eleifend中的Phasellus faucibus nulla。 Cras tristique augue eget libero tristique condimentum。 Mauris eget diam eget risus feugiat rutrum。 Duis placerat lorem quis augue semper porttitor。 Nullam iaculis dui feugiat erat condimentum rutrum。在累积直径的Sed。 Maecenas ut urna id velit posuere auctor in vel dui。 Aeoan consectetur dui在leo faucibus sed feugiat dui blandit。在accumsan diam vitae erat volutpat volutpat aliquam nunc euismod。 Vivamus viverra lorem nulla。 Quisque justo quam,adipiscing坐在amet auctor non,laoreet sit amet nisl。 Donec euismod lorem ac mi dictum volutpat。 Donec ligula mi,varius ac auctor at,sollicitudin id elit。在auctor sodales ipsum nec consectetur。 Sed lacinia varius nibh vitae vulputate。

如果我将鼠标光标悬停在第一个单词“Lorem”上,我希望它变为粗体(例如)。基本上,我只希望光标所在的文本在鼠标悬停时添加一个CSS属性,然后在光标不再位于该单词之上时删除该CSS属性。

我能想到这样做的唯一方法是在每个单词之间添加<span>标记。这是唯一的方法吗?是否有更有效的方法,或jQuery的鼠标悬停事件只能在标签内工作?它可以用于识别文本块吗?

6 个答案:

答案 0 :(得分:20)

对于http://letteringjs.com/

来说,这似乎是一项很好的任务

您可以将其设置为在字障碍处为您创建跨度。

JSFiddle与您的示例:http://jsfiddle.net/3HdKH/

从他们的教程:https://github.com/davatron5000/Lettering.js/wiki/Wrapping-words-with-lettering%28%27words%27%29

使用:

$(document).ready(function() {
  $(".word_split").lettering('words');
});

<p class="word_split">Don't break my heart.</p>

变为:

<p class="word_split">
  <span class="word1">Don't</span>
  <span class="word2">break</span>
  <span class="word3">my</span>
  <span class="word4">heart.</span>
</p>

然后你可以使用以下CSS:

.word_split span:hover {
    font-weight:bold;
}

答案 1 :(得分:1)

$("p:contains(Lorem)").each(function(){
  $(this).html($(this).text().replace(/(Lorem)/, '<span class="highlightWord">$1</span> '));
});

取自here

答案 2 :(得分:1)

$('span').each(function(){
    $(this).html(
            $(this)
                .text()
                .split(' ')
                .map(function(x){return "<word>"+x+"</word>";})
                .join(' ')
       )
});
$('word').hover(function(){
        $(this).css(/*highlight*/);            
},function(){
        $(this).css(/*de-highlight*/);   
});

答案 3 :(得分:0)

你可以做到这一点的唯一方法是使用跨度(正如你所描述的)。 Javascript将文本块视为一个元素,除非它被破坏。你只能对元素做事。由于所有文本流和剂量都有一个位置,因此您无法确定单个单词的位置以查看其何时悬停。除非您的文字很大,否则一些额外的跨度中断不应该是性能的大问题。

答案 4 :(得分:0)

这是我能想到的唯一方法。您可以使用鼠标事件和鼠标位置(尝试找出该位置的单词)来执行某些操作,但这不是最有趣的尝试。您可能需要在单词周围添加一些标记作为参考点。

如果您打算将其分解为我建议使用单个字符标记的元素,例如<p>

另一个中间选项是仅容器上的over事件,并且只有在用户悬停时才将文本分解为子元素。类似的东西:

$('#container').live('mouseenter',function(){
var jThis = $(this);
var text = jThis.text();
jThis.attr('original',text);
text = text.split(' ');
var out_text = '';
for(var nI = 0; nI < text.length; nI++){
out_text += "<p>"+text[nI]+"</p>";
}
jThis.html(out_text);
});
$('#container p').live('mouseenter',function(){
$(this).addClass('highlight');
});

你也需要添加out事件。

答案 5 :(得分:0)

这是我使用过的一种技术,它在父元素中的所有单词周围包含span标签,以便在悬停时突出显示它们:

&#13;
&#13;
const parentElement = document.getElementById('parent');

parentElement.onmouseover = e => {
  e.target.innerHTML = e.target.innerText.replace(/([\w]+)/g, '<span>$1</span>');
};
&#13;
p#parent span:hover {
  background: yellow;
  cursor: pointer;
}
&#13;
<p id="parent">One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me?" he thought. It wasn't a dream. His room, a proper human room although a little too small, lay peacefully between its four familiar walls. A collection of textile samples lay spread out on the table - Samsa was a travelling salesman - and above it there hung a picture that he had recently cut out of an illustrated magazine and housed in a nice, gilded frame. It showed a lady fitted out with a fur hat and fur boa who sat upright, raising a heavy fur muff that covered the whole of her lower arm towards the viewer. Gregor then turned to look out the window at the dull weather. </p>
&#13;
&#13;
&#13;

此代码为列表项中的单词添加了一个单击处理程序:

parentElement.onmouseover = e => {
  if (e.target.nodeName === 'LI') {
    e.target.innerHTML = 
      e.target.innerText.replace(/([\w]+)/g, '<span>$1</span>');
    e.target.onclick = e => {
      doSomething(e.target.textContent);
    };
  }
}