使用javascript检测文本并更改背景颜色

时间:2018-03-25 18:37:24

标签: javascript html

您好我的朋友,我有以下代码:

<div class='post-inner'>
<span class='item_status'>Sold</span>
<span class='item_status>Offer</span>
</div>

我希望使用javascript更改每个文本的背景颜色。

例如:

使用javascript检测已售出文字,然后更改红色背景色。

使用javascript检测优惠文字,然后更改蓝色背景颜色。

谢谢你

4 个答案:

答案 0 :(得分:1)

Without making modifications to the structure of the HTML up front, you're going to have to read all of the text and then isolate the words to be styled by wrapping them with <span> elements and then have CSS styles applied to them.

let elementToBeSearched = document.querySelector(".post-inner");

// Begin traversing the child elements as an array
Array.prototype.slice.call(elementToBeSearched.children).forEach(function(node){
  // Replace keywords with span elements that are tied to the correct CSS class.
  node.innerHTML = node.innerHTML.replace(/Sold/g, "<span class='sold'>Sold</span>");
  node.innerHTML = node.innerHTML.replace(/Offer/g, "<span class='offer'>Offer</span>");
});
.sold { color:red; }
.offer { color:green; }
<div class='post-inner'>
  <span class='item_status'>Sold Item</span>
  <span class='item_status'>Offer</span>
  <div>
    This is some other random element that may contain lots of words, including
    the words Sold and Offer.
  </div>
</div>

答案 1 :(得分:0)

根据值更改颜色不是一个好选择。

为了呈现此字符串(已售出或已提供),您应该知道该项目的状态。这意味着您可以根据项目的状态添加不同的CSS类,然后在CSS类中应用颜色。

答案 2 :(得分:0)

What we're doing here is looping over all elements with class item_status checking the inner text if it contains the word then adding a class based on that

document.querySelectorAll('.item_status').forEach(i => {
  i.textContent.indexOf("Sold") !== -1 ?
    i.classList.add('red') :
    i.innerText.indexOf("Offer") !== -1 ?
    i.classList.add('green') :
    null;
});
.red {
  color: red
}
.green {
  color: green;
}
   
<div class='post-inner'>
<span class='item_status'>Sold</span>
<span class='item_status'>Offer</span>
</div>

答案 3 :(得分:0)

var items = document.getElementsByClassName("item_status");

for(let i = 0; i<items.length; i++){
  if(items[i].innerHTML === "Sold"){
    items[i].style.color = "red";
  }
  else{
    items[i].style.color = "blue";
  }
}