为了账号安全,请及时绑定邮箱和手机立即绑定

动态地将类添加到跨度的特定部分

动态地将类添加到跨度的特定部分

一只萌萌小番薯 2022-10-21 09:44:38
我想动态地将一个类添加到定义跨度的特定句子中。假设我想focusColorClass在 span 的这句话中添加 CSS 类:不告诉我你怎么能这样?!我们怎样才能做到这一点?我试过这个没有运气!const selectSpan = document.getElementById('dialogue-span')const sentence = "How could you do this without telling me?!";selectSpan.innerHTML = selectSpan.innerHTML.replace(new RegExp('(' + sentence + ')'), `<span class="focusColorClass">${sentence}</span>`);  .focusColorClass {  color: red;}<div id="answerSentence" class="answerSentence-class"><span id="dialogue-span">You pirced her ears. How could you do this without telling me?! Now if I had told you Then it would'nt have been a surprise! now would it?! I think she looks cute... But I'm wrong!!!</span></div>
查看完整描述

3 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

使用replace功能。这会用您的代码替换您正在寻找的句子。


const selectSpan = document.getElementById('dialogue-span')

const sentence = "How could you do this without telling me?!";

selectSpan.innerHTML = selectSpan.innerText.replace(sentence, `<span class="focusColorClass">${sentence}</span>`);

.focusColorClass {

  color: red;

}

<div id="answerSentence" class="answerSentence-class">


<span id="dialogue-span">You pirced her ears. How could you do this without telling me?! Now if I had told you Then it would'nt have been a surprise! now would it?! I think she looks cute... But I'm wrong!!!</span>


</div>


查看完整回答
反对 回复 2022-10-21
?
婷婷同学_

TA贡献1844条经验 获得超8个赞

const selectSpan = document.getElementById('dialogue-span')

const sentence = "How could you do this without telling me?!";

selectSpan.innerHTML = selectSpan.innerHTML.replace(sentence, `<span class="focusColorClass">${sentence}</span>`);

.focusColorClass {

  color: red;

}

<div id="answerSentence" class="answerSentence-class">


<span id="dialogue-span">You pirced her ears. How could you do this without telling me?! Now if I had told you Then it would'nt have been a surprise! now would it?! I think she looks cute... But I'm wrong!!!</span>


</div>


查看完整回答
反对 回复 2022-10-21
?
冉冉说

TA贡献1877条经验 获得超1个赞

您可以获取内容中句子的开始和结束索引,并使用颜色类为其添加span父substring级,如下所示:


const selectSpan = document.getElementById('dialogue-span');

const sentence = "How could you do this without telling me?!";

let content = selectSpan.innerHTML;

let start = content.indexOf(sentence), end = start+sentence.length;

console.log(start,end);

if(start>-1)

     selectSpan.innerHTML = content.substring(0,start) + `<span class="focusColorClass">${sentence}</span>` + content.substring(end,content.length);

.focusColorClass {

  color: red;

}

<div id="answerSentence" class="answerSentence-class">


<span id="dialogue-span">You pirced her ears. How could you do this without telling me?! Now if I had told you Then it would'nt have been a surprise! now would it?! I think she looks cute... But I'm wrong!!!</span>


</div>


查看完整回答
反对 回复 2022-10-21
  • 3 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信