如果在同一个div上触发了均匀的“鼠标悬停”,如何更改div颜色?纯JS

时间:2017-09-15 20:38:59

标签: javascript html css

var changeDiv = document.getElementsByClassName("run")[0];

function changeColor(style) {

  var colors = ["green", "blue", "yellow"];
  for (var i = 0; i < colors.length; i++) {
    style.style.backgroundColor = colors[i];
    break;
  }
}

changeDiv.addEventListener("mouseover", function() {
  changeColor(this);
}, false);
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div class="run">

    e3reerghdhf </b>

    djdhfdgfdgdhhghgd
  </div>
</body>

</html>

我希望换成一种颜色,我想悬停在div上并改变颜色,每次我悬停或(鼠标悬停)。我想也许我不得不使用windowSessionStorage来保存索引并在触发事件时更改其值。

3 个答案:

答案 0 :(得分:2)

您可以将变量存储在js中,如下所示:

&#13;
&#13;
var changeDiv = document.getElementsByClassName("run")[0];

var colors = ["green", "blue", "yellow"];
var i = 0;

function changeColor(style) {

  style.style.backgroundColor = colors[i];
  if (i < colors.length - 1) {
    i++
  }
  else {
    i = 0;
  }

}

changeDiv.addEventListener("mouseover", function() {
  changeColor(this);
}, false);
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <div class="run">

    e3reerghdhf </b>

    djdhfdgfdgdhhghgd
  </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用Javascript完全实现该行为,但为什么要实现一些可以使用单行基本CSS轻松完成的事情?

.run:hover{ background-color:red;}

编辑: 使用颜色列表更改每个翻转的颜色。 您可以使用数组和索引指针,并在每次触发事件时递增指针:

https://jsfiddle.net/ydrr0xn8/

&#13;
&#13;
var changeDiv = document.getElementsByClassName("run")[0];

changeDiv.addEventListener("mouseover", function() {
  var colors = ['red', 'green', 'blue'];
  var index = colors.indexOf(changeDiv.style.backgroundColor) + 1;
  if (index >= colors.length || index === -1) index = 0;
  changeDiv.style.backgroundColor = colors[index];
}, false);
&#13;
<div class="run">ff</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是一个通过不同背景颜色进展的解决方案在未被徘徊时重置为原始背景。

function colorChange( el, colors ) {
  
  var i         = 0,
      baseColor = el.style.backgroundColor;  

  el.addEventListener( 'mouseenter', function () {
    this.style.backgroundColor = colors[ i++ % colors.length ];
  } );

  el.addEventListener( 'mouseleave', function () {
    this.style.backgroundColor = baseColor;
  } );
    
}
var colors = [ 'red', 'blue', 'yellow' ];
var p      = document.querySelector( 'p' );

colorChange( p, colors );
<p>Hello world!</p>