单击并在鼠标上方更改div背景

时间:2015-04-26 20:42:59

标签: javascript html css

我正在尝试使用JS在鼠标上单击并更改div中的图片。像那样:

    var favs = document.getElementsByClassName("fav-wrapper");
    for (var i = 0; i < favs.length; i++) {
    favs[i].innerHTML = '<img src="images/favorite.png" />';
    favs[i].onMouseOver = function () {
        favs[i].innerHTML = "<img src='images/favorite_hover.png' />";
    }
    favs[i].onClick = function () {
        favs[i].innerHTML = "<img src='images/favorite_on.png' />";
    };
}

但由于某种原因它不起作用。我做错了什么?

2 个答案:

答案 0 :(得分:3)

尝试使用小写事件处理程序,实际上你需要一个闭包让[i]在循环中工作。我更喜欢在你的情况下使用this

var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < favs.length; i++) {
  favs[i].innerHTML = '<img src="images/favorite.png" />';
  favs[i].onmouseover = function () {
    this.innerHTML = "<img src='images/favorite_hover.png' />";
  }
  favs[i].onclick = function () {
    this.innerHTML = "<img src='images/favorite_on.png' />";
  }
}

但为什么不改变图像的src?

var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < favs.length; i++) {
  var fav=favs[i];
  fav.getElementsByTagName("img")[0].src="images/favorite.png";
  fav.onmouseover = function () {
    this.getElementsByTagName("img")[0].src="images/favorite_hover.png";
  }
  fav.onmouseout = function () {
    this.getElementsByTagName("img")[0].src="images/favorite.png";
  }
  fav.onclick = function () {
    this.getElementsByTagName("img")[0].src="images/favorite_on.png";
  }
}

你可以通过CSS来完成所有这些

答案 1 :(得分:2)

您可以在悬停时使用纯css更改背景并单击

来尝试此方法

.image{width:500px;height:500px;background-image: url("http://www.toolsformoney.com/financial_software_demos.jpg");background-repeat: no-repeat;}
.image:hover{background-image: url("http://www.hostpph.com/blog/wp-content/uploads/2012/06/free-bookie-software-demo-large.jpg");background-repeat: no-repeat;}
.image:focus{background-image: url("https://www.arxan.com/wp-content/uploads/assets1/images/demo.png");background-repeat: no-repeat;outline: 0;transition:0s;}
<div class="image" tabindex="0">
</div>