简体   繁体   English

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

[英]Highlight an individual word within a text block on hover

In javascript/jQuery, is there a way to identify a word in a text block/paragraph?在 javascript/jQuery 中,有没有办法识别文本块/段落中的单词? For example, say I have the following paragraph:例如,假设我有以下段落:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor 坐 amet,consectetur adipiscing 精英。 Mauris suscipit interdum fermentum. Mauris suscipit interdumfermentum。 Aenean fermentum imperdiet augue, et venenatis lectus semper vel.埃涅斯酵母菌 imperdiet augue, et venenatis lectus semper vel。 Phasellus faucibus nulla in quam egestas eleifend. Phasellus faucibus nulla in quam egestas eleifend。 Cras tristique augue eget libero tristique condimentum. Cras tristique augue eget libero tristique 调味品。 Mauris eget diam eget risus feugiat rutrum. Mauris eget diam eget risus feugiat rutrum。 Duis placerat lorem quis augue semper porttitor. Duis placerat lorem quis augue semper porttitor。 Nullam iaculis dui feugiat erat condimentum rutrum. Nullam iaculis dui feugiat rat condimentum rutrum。 Sed at accumsan diam. sed 在 accumsan 直径。 Maecenas ut urna id velit posuere auctor in vel dui. Maecenas ut urna id velit posuere auctor in vel dui。 Aenean consectetur dui in leo faucibus sed feugiat dui blandit. Aenean consectetur dui in leo faucibus sed feugiat dui blandit。 In accumsan diam vitae erat volutpat volutpat aliquam nunc euismod.在 accumsan diam vitae 中 volutpat volutpat aliquam nunc euismod。 Vivamus viverra lorem nulla. Vivamus viverra lorem nulla。 Quisque justo quam, adipiscing sit amet auctor non, laoreet sit amet nisl. Quisque justo quam,adipiscing 坐在 amet amet auctor non,laoreet 坐在 amet nisl。 Donec euismod lorem ac mi dictum volutpat. Donec euismod lorem ac mi dictum volutpat。 Donec ligula mi, varius ac auctor at, sollicitudin id elit. Donec ligula mi,varius ac auctor at,sollicitudin id elit。 In auctor sodales ipsum nec consectetur.在作者 sodales ipsum nec consectetur。 Sed lacinia varius nibh vitae vulputate. Sed lacinia varius nibh vitae vulputate。

If I hover my mouse cursor over the first word, "Lorem", I would like it to become bold (for example).如果我将鼠标光标悬停在第一个单词“Lorem”上,我希望它变成粗体(例如)。 Basically, I would like just the text that the cursor is over to have a CSS property added to it on mouseover, then have that CSS property removed when the cursor is no longer on top of that word.基本上,我只希望光标所在的文本在鼠标悬停时添加一个 CSS 属性,然后在光标不再位于该单词的顶部时删除该 CSS 属性。

The only way I can think of doing this is to add a <span> tag between each and every word.我能想到的唯一方法是在每个单词之间添加一个<span>标签。 Is this the only way?这是唯一的方法吗? Is there a more efficient way perhaps, or does jQuery's mouseover event only work within tags?也许有更有效的方法,或者 jQuery 的鼠标悬停事件是否只在标签内工作? Can it work in identifying text blocks?它可以识别文本块吗?

This seems like a good task for http://letteringjs.com/这对http://letteringjs.com/ 来说似乎是一项好任务

You can set it up to create the spans for you at word barriers.您可以将其设置为在单词障碍处为您创建跨度。

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

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

Using:使用:

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

This

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

Becomes:变成:

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

Then you can use the following CSS:然后您可以使用以下 CSS:

.word_split span:hover {
    font-weight:bold;
}
$('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*/);   
});

Here's a technique I've used that wraps span tags around all words in a parent element so that they can be highlighted on hover:这是我使用的一种技术,它在父元素中的所有单词周围包裹 span 标签,以便它们可以在悬停时突出显示:

 const parentElement = document.getElementById('parent'); parentElement.onmouseover = e => { e.target.innerHTML = e.target.innerText.replace(/([\\w]+)/g, '<span>$1</span>'); };
 p#parent span:hover { background: yellow; cursor: pointer; }
 <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>

This code adds a click handler for words in list items:此代码为列表项中的单词添加了一个单击处理程序:

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

This taken from here这是从这里拍摄的

The only way you can do this is with spans (as you described).您可以做到这一点的唯一方法是使用跨度(如您所描述的)。 Javascript sees the block of text as one element unless its broken up. Javascript 将文本块视为一个元素,除非它被分解。 You can only do things on elements.你只能在元素上做事。 Since all the text flows and dosent have a position you cant pinpoint the individual word position to see when its hovered.由于所有文本流和 dosent 都有一个位置,因此您无法确定单个单词的位置以查看其悬停时间。 Unless your text is huge a few extra span breaks shouldn't be a big issue for performance.除非您的文本很大,否则一些额外的跨度中断对性能来说应该不是一个大问题。

That is the only way I can think of.这是我能想到的唯一方法。 You might be able to do something using mouse events and mouse location (attempt to figure out what word is at the location), but it wouldn't be the funnest thing to try.您也许可以使用鼠标事件和鼠标位置来做一些事情(尝试找出该位置上的单词),但这并不是最有趣的尝试。 You'd probably need to add some tags around words for reference points.您可能需要在单词周围添加一些标签作为参考点。

If you're going to break it up into elements I'd suggest using a single character tag, like <p> .如果您要将其分解为元素,我建议您使用单个字符标签,例如<p>

Another in-between option would be to just the over event on the container, and only break the text into sub-elements if the user hovers.另一个介于两者之间的选项是容器上的 over 事件,并且只有在用户悬停时才将文本分解为子元素。 Something like:就像是:

$('#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');
});

You'd need to add the out events too.您还需要添加 out 事件。

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

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