问题
I have a thumbnail image.
Upon mousing over this image, an entirely new image appears nearby, as intended.
THE CHALLENGE
The new image must remain once the hovering of the thumbnail is over. The new image should only disappear when the user mouses away from the new image.
CSS-only Solution
After experimenting for hours with CSS today, the best solution I devised involved the :hover
pseudo-class, transition
, and opacity
. It's convoluted and complicated solution for what may be a simple task in JS. PLUS, the solution isn't even that great and may only work in newer browsers. So I've moved away from searching for a CSS-only solution (although I'm open to your ideas on this).
JAVASCRIPT
I don't know JS very well, but I've come up with some code (probably poorly structured) that's gotten me closer to the goal. The JS I have in place right now fires the new image on thumbnail mouseover, and hides the new image on mouseleave.
The problem is that the code doesn't reset (so the user would have to refresh the page for the hover effect to work again).
Here's what I have so far:
HTML
<ul>
<li id="thumbnail">
<a href="#">THUMBNAIL IMAGE</a>
<ul>
<li>
<a href="#">NEW IMAGE NEARBY</a>
</li>
</ul>
</li>
</ul>
CSS
ul > li > ul {display: none;}
ul > li#thumbnail > a {
background-color: #f00;
color: #fff;
padding: 5px;
}
ul > li > ul > li {
position: absolute;
top: 50px;
left: 175px;
background-color: #0f0;
color: #fff;
padding: 15px;
}
ul li ul.permahover {display: block;}
JavaScript
$("#thumbnail").one("mouseover", function() {
$("#thumbnail ul").addClass('permahover');
});
$("#thumbnail ul").mouseleave(function(){
$(this).hide();
});
http://jsfiddle.net/nyc212/Ey2bK/2/
Any help would be greatly appreciated. Thank you.
回答1:
The reason why it isn't resetting that you're using one(), The handler attached using one()
is executed at most once per element per event type.
Try using on() instead as follows:
$("#thumbnail").on("mouseover", function () {
$("#thumbnail ul").addClass('permahover');
});
$("#thumbnail ul").mouseleave(function () {
$("#thumbnail ul").removeClass('permahover');
});
Updated Fiddle
Side note: on()
isn't available prior jQuery 1.71, hence i updated the version of jQuery in fiddle,( on()
is the recomended method for attaching event handlers as of now) For older version of jQuery you can use bind()
来源:https://stackoverflow.com/questions/24836640/hover-over-thumbnail-image-to-launch-new-image-new-image-persists-after-hoverin