悬停时高亮显示文本块中的单个单词

Highlight an individual word within a text block on hover

本文关键字:单个单 文本 高亮 显示 悬停      更新时间:2023-09-26

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

Lorem ipsum悲哀坐amet,consectetur adipiscing elit。Mauris suscipit interdum fermentum。埃涅阿斯纪是一个预兆,而威尼斯则是一个选择。Phasellus faucibus nulla in quam egestas eleifend。Cras tristique auge eget libero tristique调味品。Mauris eget diam eget risus feugiat rutrum。Duis砂矿开采商lorem quis auge semper porttitor。Nullam iaculis dui feugiat erat调味品钌。Sed at accumsan diam Maecenas ut urna id velit posuere auctor in vel dui。埃涅阿斯在《狮子座》中的consectetur dui sed feugiat dui blandit。在accumsan diam vitae erat volutpat volutbat aliquam nunc euismod。Vivamus viverra lorem nulla。Quisque justo quam,adipiscing坐amet auctor non,laoreet坐amet nisl。Donec euismod lorem ac mi dictum volutpat。Donec ligula mi,varius ac auctor at,sollicitudin id elit。在拍卖行苏打水ipsumnecconsectetur。花叶景天。

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

我能想到的唯一方法是在每个单词之间添加一个<span>标签。这是唯一的路吗?有没有更有效的方法,或者jQuery的mouseover事件只在标记中工作?它能识别文本块吗?

对于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;
}

以下是我使用的一种技术,它将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>

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

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

这是从这里获取的

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

实现这一点的唯一方法是使用跨度(如您所述(。Javascript将文本块视为一个元素,除非它被分解。只能对元素执行操作。由于所有的文本流和dosent都有一个位置,所以当它悬停时,你无法精确定位单个单词的位置。除非你的文本很大,否则额外的几次跨度中断对性能来说应该不是什么大问题。

这是我唯一能想到的方法。你可能可以使用鼠标事件和鼠标位置来做一些事情(试图弄清楚这个位置上的单词是什么(,但这不是最有趣的尝试。你可能需要在单词周围添加一些标签作为参考点。

如果要将其分解为多个元素,我建议使用单字符标记,如<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事件。