Pregunta

So I'm trying to get a onMouseOver to replace an image when the mouse is hovering over a div, unfortunately, as I have it right now it only replaces the image when the mouse is directly over the image, not the div, is there a way to get this to work?

Should I use a CSS to place the image, and replace the image on hover instead?

<div class="link">
     <a href="link.html">
          <img src="img.png" onMouseOver="this.src='hoverimg.png'" onMouseOut="img.png'"
          <div class="title">Title</div>
     </a>
</div>
¿Fue útil?

Solución

I prefer using CSS for this:

<div class="image-hover">
    Some title
</div>

.image-hover { background: url(...);}
.image-hover:hover { background: url(...);}

Otros consejos

This can be achieved with CSS and background images. You also should not be using a block level element (div) inside of an inline element (a). I've swapped it for a span. For example:

<style type="text/css">
.link a {
    display:inline-block;
    background: url('img.png') top left no-repeat;
    width:(imagewidth)px;
    padding-top:(imageheight)px;
}
.link a:hover {
    background: url('hoverimg.png') top left no-repeat;
}
</style>

<div class="link">
     <a href="link.html">
          <span class="title">Title</span>
     </a>
</div>

The complete optimum would be combining the two images into what is called a sprite and use background-position.

You can do this with CSS or jQuery. Most people will recommend that you use CSS because it is easier to debug:

If you want the image to change when you hover on the div, you can apply a :hover state to the div:

.link img{
    background: url("image1.png");
}

.link:hover img
{
    background: url("image2.png");
}

However you should note that this basically treats img as an inline-block element and does not change the src attribute.


jQuery will allow you to change the source, but it must be debugged if something goes wrong, and if JS is disabled, it will not run.

$(".link").hover(function(){
    $(this).find("img").attr("src", "image2.png");
}).mouseout(function(){
    $(this).find("img").attr("src", "image1.png");
});

JSFiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top