Java脚本切换div的颜色

时间:2019-02-22 04:50:35

标签: javascript onmouseover

以下脚本正在创建一个16格的网格。对于每个mouseover效果,我想永久更改div的颜色。有人可以给我一个指针,changeColor的功能是什么样的吗?

<script>

let gridcontainer = document.querySelector('#gridcontainer');
gridcontainer.setAttribute('style', 'width: 20px; display: grid; grid-template-columns: auto auto auto auto;')

var index = [];
var boxes;
var i;
var change;

function createGrid(){                     
  for(i=0;i<16;i++){


                                          //console.log(index);

    boxes = document.createElement('div');
                                          console.log(boxes);
    boxes.classList.add('boxes');
    boxes.setAttribute('style','width: 30px; height:30px; background-color: 
    blue; margin: 5px;');
    boxes.setAttribute('onmouseover', changeColor());
    gridcontainer.appendChild(boxes);  

  }}

  function changeColor(){
  change = document.querySelector('.boxes');
  change.setAttribute('style','background-color: red');

  }
</script>

谢谢大家的帮助。

2 个答案:

答案 0 :(得分:-1)

您可以像下面这样使用$string = 'my(apple)[banana][carrot(orange)]food[supply]{test}'; echo preg_replace('/{(.*?)}|\[.*?\]|\([^)]+\)/","",$string);

document.getElementsByClassName
function changeColor() {
  change = document.getElementsByClassName('boxes');
  for (let i = 0; i < change.length; i++) {
    change[i].setAttribute('style', 'background-color: red');
  }
}

changeColor();
.boxes {
  width: 50px;
  height: 50px;
  background-color: yellow;
}

答案 1 :(得分:-1)

我已经使用jquery函数(toggleClass)来更改悬停时的颜色div

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style type="text/css">
    .b1{
        background:red;
        width: 30px;
        height: 40px;
        margin: 10px;
    }
    .b{
        background:blue;
        width: 30px;
        height: 40px;
        margin: 10px;
    }
    </style>
</head>
<body>
    <div class="b1"></div>
    <div class="b1"></div>
    <div class="b1"></div>
    <div class="b1"></div>
    <div class="b1"></div>
<script type="text/javascript">
    $('div').hover(function () {
        // body...
         $("div").toggleClass("b");
    });
</script>
</body>
</html>