changing link image on hover

2019-09-18 14:09发布

问题:

my question today probably has an easy answer, however I have found a few working examples but can't seem to transfer it to my web page.

I am trying to use an image for a link, and would like the image to change when you hover over it. The link below is what I am trying to accomplish, but for whatever reason when I substitute my code from my page to it, it doesn't work.

EXAMPLE http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onmouseover

I am completely lost now and just need a little help. Here is my code.

DEMO

function hoverImg(x) {
  x.style.backgroundImage = "url(image/arrowBtnHover.png)"
  x.style.transition = "ease 0.5s"
}

function normalImg(x) {
  x.style.backgroundImage = "url(image/arrowBtn.png)"
}
#header {
  background-color: #473D39;
  height: 100%;
  width: 100%;
  display: table;
  position: absolute;
  z-index: 10;
}
#wrapper {
  display: table-cell;
  vertical-align: middle;
}
#header h1 {
  text-align: center;
  margin: 0px;
  font-size: 80px;
  padding-top: 5%;
  font-weight: normal;
  color: #FFF;
  letter-spacing: 18px;
  text-transform: uppercase;
}
#header h5 {
  text-align: center;
  color: #FFF;
  margin: 15px 15px 50px;
  font-weight: normal;
  text-transform: uppercase;
  font-size: 14px;
  letter-spacing: 2px;
}
<div id="header">
  <div id="wrapper">
    <h1>Premier Webster</h1>
    <h5>Local Web Design For The Profesional In You</h5>
    <img onmouseover="hoverImg(this)" onmouseout="normalImg(this)" src="image/arrowBtn.png" />
  </div>
</div>

回答1:

Please take a look at https://jsfiddle.net/avzfdc2j/3/

It has been done using css with background image and transition

div.smile {
    background-image: url("http://images.clipartpanda.com/stupidity-clipart-1320682287266972230curius_face.svg.hi.png");
    background-size: 60px 60px;
    height: 60px;
    width: 60px;
    cursor: pointer;
}

div.smile:hover {
    background-image: url("http://images.clipartpanda.com/straight-face-clipart-black-and-white-smiley-face-hi.png");
    transition: ease 0.5s;
}

<a href="http://google.com/"><div class="smile"></div></a>


回答2:

You should be changing the src attribute instead:

function hoverImg(x) {
    x.src = "image/arrowBtnHover.png"
    x.style.transition = "ease 0.5s"
}

function normalImg(x) {
    x.src = "image/arrowBtn.png"
}

But I don't think that the transition will work with this.



回答3:

Since it's an image, you need to change it's src property, not it's CSS.

function hoverImg(x) {
    x.src = "image/arrowBtnHover.png"
    x.style.transition = "ease 0.5s"
}

function normalImg(x) {
    x.src = "image/arrowBtn.png"
}