javascript - 更改 div 中包裹的字符串特定部分的颜色

标签 javascript html css regex

如何更改 div 中包裹的字符串的特定部分的颜色:

我们有一个这样的 div:

<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers </div>

我们如何使用下面的代码模板将“可信在线社区”部分的颜色更改为红色?

let text = document.getElementById("text");

// We want to only change the color of this portion of the text
changeColor('trusted online community');


function changeColor(portion){

    // code to change the text color
    ...
    
    // function to animate the color from black to red
    function changeToRed(el) {
		el.classList.add("colorRed");
    }
    
};
.colorRed {
    animation: colorRedAnime 0.8s cubic-bezier(0.785, 0.135, 0.15, 0.86);  
    animation-fill-mode: forwards ;
}

@-webkit-keyframes colorRedAnime {
  from { color: #808080 }
  to   { color: #e80000 }
}
<div class="container"> 
<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers </div>
</div>

最佳答案

您需要创建一个SPAN并将其添加到(内部)html

var lookFor = 'trusted online community';
var idx = text.innerHTML.indexOf(lookFor); //you could use regex also as an alternative
text.innerHTML = text.innerHTML.substring(0, idx) + '<span class="colorRed">' + lookFor + '</span>' + text.innerHTML.substring(idx + lookFor.length);

关于javascript - 更改 div 中包裹的字符串特定部分的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60007856/

相关文章:

jquery - 当 slider 位于固定定位元素内时,FlexSlider 不缩放向下滑动

javascript - Webpack 将 scss 编译为 css 并缩小

javascript - HTML5站点在silk浏览器中进入全屏模式还是在加载url后在silk浏览器中隐藏地址栏?

html - 使用 Flexbox 和 Overflow 使元素居中

javascript - Angular 选择未从 ng-model 分配中获取设置

javascript - Ionic - ion-nav-view 在模拟器中崩溃

javascript - 将 reddit 的 'created' unix 时间戳转换为可读日期

javascript - 在 Angular 中从 nodejs 获取 JSON

html - 边界问题

javascript - div 循环隐藏和显示