问题
I have this code:
$("document").ready( function () {
$(".userPic").mouseover(function () {
$(".changePic img").css("display", "block");
})
$(".userPic").mouseout(function () {
$(".changePic img").css("display", "none");
})
})
I have 2 DIVs and 1 image inside each them.
My problem is when you mouseover .changePic (which is inside .userPic) the mouseout event will fire and the image will not be displayed.
How I can apply the mouseover to all elements inside the main DIV .userPic? So when you mouseover the images and .changePic, the image will still be displayed and the mouseout event will not fire.
How can it be done?
HTML code:
<div class="accountPic">
<div class="userPic">
<img src="images/userPhoto.png" alt="" width="236" height="200" />
</div>
<div class="changePic"><a href="editUsers.php"><img style="display: none;" src="images/config.png" alt="" width="13" height="14" border="0" /></a></div>
</div>
回答1:
If you don't need to support IE6, you can do this without JavaScript (see below). First, though, the JavaScript + jQuery answer:
Using jQuery
You want to use mouseenter and mouseleave instead of mouseover
and mouseout
. mouseover
and mouseout
bubble, so when they fire on elements within the element you're watching, you receive them at the element you're watching. It can get complicated quickly. mouseenter
and mouseleave
only happen when the mouse enters or leaves the specific element in question (they don't bubble). Originally they were IE-specific events, but jQuery emulates them on browsers that don't support them natively.
Separately, are you sure you really want to operate on all of the img
elements in all of the elements with the "changePic" class? Or only the ones within the specific element your mouse is over? If the latter, you also want to update your code to use find
, like so:
jQuery(function($) {
$(".userPic").mouseover(function () {
$(this).find(".changePic img").css("display", "block");
});
$(".userPic").mouseout(function () {
$(this).find(".changePic img").css("display", "none");
});
});
Live example
Using CSS
But note that you can do this with CSS unless you need to support IE6. Just use style rules:
.userPic .changePic img {
display: none;
}
.userPic:hover .changePic img {
display: inline;
}
Live example
No JavaScript required. But the hover
pseudo-class doesn't work in IE6 except on a
elements. (Be sure to remove the inline style="display: none"
that I assume you currently have on the images.)
来源:https://stackoverflow.com/questions/5066042/jquery-mouseover-event-not-working-right