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? For example, say I have the following paragraph:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris suscipit interdum fermentum. Aenean fermentum imperdiet augue, et venenatis lectus semper vel. Phasellus faucibus nulla in quam egestas eleifend. 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 at accumsan diam. Maecenas ut urna id velit posuere auctor in vel dui. Aenean consectetur dui in leo faucibus sed feugiat dui blandit. In accumsan diam vitae erat volutpat volutpat aliquam nunc euismod. Vivamus viverra lorem nulla. Quisque justo quam, adipiscing sit amet auctor non, laoreet sit amet nisl. Donec euismod lorem ac mi dictum volutpat. Donec ligula mi, varius ac auctor at, sollicitudin id elit. In auctor sodales ipsum nec consectetur. 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). 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.
The only way I can think of doing this is to add a <span>
tag between each and every word. Is this the only way? Is there a more efficient way perhaps, or does jQuery's mouseover event only work within tags? Can it work in identifying text blocks?
This seems like a good task for 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/
From their tutorial: 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:
.word_split span:hover {
font-weight:bold;
}
$("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*/);
});
链接地址: http://www.djcxy.com/p/88576.html
上一篇: 正确的JSON响应输出内部Div
下一篇: 悬停时突出显示文本块中的单个单词