开发者

Using jQuery, how do you change the image on hover inside of a div?

开发者 https://www.devze.com 2022-12-27 20:25 出处:网络
I have the following jQuery code to replace an image when you hover over with the mouse but it doesn\'t seem to be working.What is w开发者_StackOverflowrong with the code below?

I have the following jQuery code to replace an image when you hover over with the mouse but it doesn't seem to be working. What is w开发者_StackOverflowrong with the code below?

$(function() {
$("div.delete img")
    .mouseover(function() {
        $(this).attr("src", "../../images/comment-hover-del.png");
    })
    .mouseout(function() {
        $(this).attr("src", "../../images/comment-del.png");
});
 });

This is my HTML:

<div class="delete" id="26"><img src="../../images/comment-del.png" border="0"></div>


You can rearrange it a bit, like this:

$(function() {
  $("div.delete").hover(function() {
     $("img", this).attr("src", "../../images/comment-hover-del.png");
  }, function() {
     $("img", this).attr("src", "../../images/comment-del.png");
  });
});

This is triggered on hover of the div, since there might be a slight flash when the image changes, resulting in the image collapsing and the mouseout firing before the next image loads. I'd assign a width/height to the <div> if you use the method above to prevent this behavior, or to the image if you use your current method.

Alternatively, you could give the div a background-image css property and the <div> itself a hover (removing the <img> completely) and do this all in CSS, like this:

div.delete { 
  width: 100px; 
  height: 100px; 
  background-image: url('../../images/comment-del.png') center;
}
div.delete:hover { 
  background-image: url('../../images/comment-hover-del.png') center;
}


Try this:

$(function() {
$("div.delete")
    .mouseover(function() {
        $(this).find('img').attr("src", "../../images/comment-hover-del.png");
    })
    .mouseout(function() {
        $(this).find('img').attr("src", "../../images/comment-del.png");
});
 });


Actually, my original code was OK but I just realized the image and div were being put there dynamically. So because of that I needed to use the live event below.

(I realized this after some good answers also didn't work, which made no sense.)

$('div.delete img').live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') {
        $(this).attr("src", "../../images/comment-del-hover.png");
    } else {
         $(this).attr("src", "../../images/comment-del.png");
    }
});


You can't do effects like this though. If you want to change src and also be able to animate it go for this:

$("#clone_el").css("z-index",2);
ele = $("#clone_el").clone().css({position:"relative","top":"-"+$("#clone_el").eq(0).height()+"px","z-index":"1"}).attr("src","/path/to/new/src");

$("#clone_el").after(ele).fadeOut();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号