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

问题描述 投票:1回答:2

我有一个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>
javascript html dom
2个回答
1
投票

这是一个你想在vanilla 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>

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>
© www.soinside.com 2019 - 2024. All rights reserved.