连续改变类的背景颜色

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

我有两类元素。我的想法是,当我鼠标移动第一个具有类box的元素时,其中第一个元素具有类blue会改变其背景颜色。具有“蓝色”类别的其他元素的背景颜色应保持不变。

function changeColor(color) {
  var x = document.getElementsByClassName("blue");
  x[0].style.backgroundColor = color;
  x[1].style.backgroundColor = color;
  x[2].style.backgroundColor = color;
}

function returnColor() {
  var x = document.getElementsByClassName("blue");
  for (i = 0; i < x.length; i++) {
	x[i].style.backgroundColor = "blue";
  }
}
.box {
  width: 200px;
  height: 200px;
  display: inline-block;
  margin: 30px;
  background-color: grey;
}

.blue {
  width: 200px;
  height: 200px;
  display: inline-block;
  background-color: blue;
  margin: 30px;
}
<div class="box" onmouseout="returnColor()" onmouseover="changeColor('green')"></div>
<div class="box" onmouseout="returnColor()" onmouseover="changeColor('yellow')"></div>
<div class="box" onmouseout="returnColor()" onmouseover="changeColor('red')"></div><br>
<br>
<div class="blue"></div>
<div class="blue"></div>
<div class="blue"></div>

Onmouseout相同的元素保留它的背景颜色。然后当我将鼠标移到box类的第二个元素时,蓝色类的第二个元素会改变它的背景颜色。 Onmouseout相同的元素保留其背景颜色等。我知道如果我为每个元素添加一个ID,我可以这样做,但我特别感兴趣的是只使用类。

从我的尝试中可以看出,我只是设法改变了整个类的背景而不是按照预期的方式单独更改每个元素。

javascript html css
2个回答
0
投票

你似乎要做的是使用第一个元素组的索引并将其传递给第二个元素组,这是相对容易的,你所要做的就是遍历元素并在javascript中附加事件,这样你就可以轻松维护索引。如下所示:

https://jsfiddle.net/fkakt7wc/7/

var x = document.getElementsByClassName("blue");
var y = document.getElementsByClassName("box");

for (var i = 0; i < y.length; i++) {
    y[i].index = i;
    y[i].onmouseover = function () {
        x[this.index].style.backgroundColor = this.getAttribute("color");
    }
    y[i].onmouseout = function () {
        x[this.index].style.backgroundColor = "blue";
    }
}

0
投票

尝试传递'this'作为第二个参数。然后,您应该获取触发事件的当前元素。

© www.soinside.com 2019 - 2024. All rights reserved.