有没有一种简单的方法可以将跨度包裹在html段落中的任意文本周围?例如,给定以下原始html:
<p>Here is a dandy block of text to color up</p>
<p> WHOAH another paragraph</p>
我想根据用户输入包装文本的任意部分。因此,一组输入可能会将其转换为
<p>Here is a <span style="background:yellow">dandy block</span> of text to color up</p>
<p> WHOAH <span style="background:green">another paragraph</span></p>
而另一组输入可能会创建
<p>Here is a<span style="background:yellow">a dandy block</span> of text to color up</p>
<p> WHOAH <span style="background:green">another</span> paragraph</p>
这个问题与这个和这个有关,然而,与我的目标的主要区别是,我希望高亮显示是永久的,而不仅仅是临时选择,我还希望它在p元素而不是文本区域内工作。
如果可能的话,我想它看起来会像使用jQuery
var innerText = $('p')[p_index].slice(char_start, char_end).text();
$('p')[p_index].slice(char_start, char_end).html(
"<span style="background:yellow">"+
innerText +
"</span>");
这将(理论上)选择p_index
段落,获取给定索引之间的范围,并将其替换为新创建的跨度,该跨度中嵌套了原始文本。这显然不起作用,因为在jQuery对象上进行下标不会返回另一个内部jQuery对象。尽管
$("p").slice(0, 1).html("<span style="background: blue">" +
$("p").slice(0, 1).text() +
"</span>");
在段落级别上做我想要的事情,但在文本内部级别上做不到。我可以使用这种方法来完成替换,根据我的字符范围完整地写下每一段,但如果有简单的方法,我将非常感谢您的建议。
$("p")[p_index]
为您提供了p_index
中该段落的实际DOM元素,因此要获得该段落的内容,您需要使用:
$("p")[p_index].innerHTML
// OR
$("p")[p_index].textContent
不过,使用jQuery会更容易。您不会使用jQuery slice()
方法将范围缩小到单个元素,而是使用.eq()
方法。试试这样的东西:
$('p').eq(p_index).html(function(i,currentText) {
return currentText.substring(0, char_start) +
"<span style="background:yellow">" +
currentText.substring(char_start, char_end) +
"</span>" +
currentText.substring(char_end);
});
当您将函数传递给.html()
方法时,jQuery会将html设置为您从该函数返回的任何内容。jQuery将元素的当前(内部)html传递给函数,以便您可以处理它
演示:http://jsfiddle.net/62HHk/
试试这个:
$('input[type=text]').keyup(function() {
var val = $.trim(this.value);
var text = $('p').text().split(' ')
$.each(text, function(i, v) {
if (v == val) {
text[i] = '<span>'+v+'</span>';
}
})
$('p').html(text.join(' '))
})
Fiddle
这应该可以工作。它可以很容易地转换为一个函数,将您要查找的单词作为参数。
jQuery.text由Ben Alman 替换
$('.text').replaceText( /hello/g, '<span classs="interesting">hello</span>' );