根据内容文本更改背景颜色

时间:2018-09-09 18:57:59

标签: javascript html dom

我有一个div,但我想根据div的背景色设置背景颜色。例如,我输入两个div类#999并将背景色设置为#999。我该如何使用纯JavaScript?

function myFunction() {
    var x = document.getElementsByClassName("test").textContent;
$(".test").attr({
"style" : "background-color: + x + ;"
});
}
.test{
  padding:5px;
  background-color:#555;
  color:white;
  display:inline-block;
}
<div class="test">#999</div>

2 个答案:

答案 0 :(得分:1)

<script>
    function setColour(e) {
        
        e.style.backgroundColor = e.innerHTML;
        
    }
</script>

<style>
    .test{
      padding:5px;
      background-color:#555;
      color:white;
      display:inline-block;
      min-width:100px;
      border:1px sloid black;
    }
</style>

    Type the colour code or name inside the div:<br><br>
    <div class="test" onkeyUp='setColour(this)' contenteditable>#999</div>

答案 1 :(得分:1)

这是您要在普通JS中执行的示例,不需要jQuery。

function changeColor(element) {
  // Get the text content of the provided element.
  const
    color = element.textContent;
  // Update the element's background color. 
  element.style.backgroundColor = color;
}

// Get all the elements from the DOM with the test CSS class. You can also
// use the getElementsByClassName if you prefer.
const
  elements = document.querySelectorAll('.test');
// Iterate over all the element and for each element call the changeColor method.
elements.forEach(changeColor);
.test{
  padding:5px;
  background-color:#555;
  color:white;
  display:inline-block;
}
<div class="test">#999</div>
<div class="test">#f00</div>