gpt4 book ai didi

javascript - 使用javascript更改任意文本的背景颜色

转载 作者:太空宇宙 更新时间:2023-11-04 04:57:22 24 4
gpt4 key购买 nike

有没有一种简单的方法可以将 span 包裹在 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>

这个问题与this one有关和 this one ,但是,与我的目标的主要区别是我希望突出显示是永久性的,而不仅仅是临时选择,我也希望它在 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]

为您提供实际的 DOM 元素,即 p_index 中的那个段落,因此要获取您需要使用的段落的内容:

$("p")[p_index].innerHTML
// OR
$("p")[p_index].textContent

不过使用 jQuery 会更容易。您不会使用 jQuery slice() 方法将范围缩小到单个元素,您会使用 .eq() method .尝试这样的事情:

$('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() method 时,jQuery 将 html 设置为您从函数返回的任何内容。 jQuery 将元素的当前(内部)html 传递给函数,以便您可以处理它。 (如果你在一个包含多个元素的 jQuery 对象上执行此操作,你的函数将为每个元素调用一次,以便它们可以单独处理。)

演示:http://jsfiddle.net/62HHk/

关于javascript - 使用javascript更改任意文本的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12138518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com