jQuery li with image fade in background (fade in class)
I'm currently using this code:
var gallery = $('ul#gallery').children();
$(gallery).filter(':even').not(':last').hover(function () {$(this).toggleClass('next')});
I'm trying to make it fade this new class in. Currently, there's an <li> with an image in it, no background. When the 'next' class is added, it gives it a background image when hovered over. Is there a way to just f开发者_开发百科ade in the new class without making the image blink/fade at all?
If you have jQueryUI installed, you can fade animate a class by adding a duration.
$(this).toggleClass('next', 500);
http://jqueryui.com/demos/toggleClass/
But as far as I know, there is no separate opacity setting that affects only the background image. So if you want to fade that in, you would need to fade the entire element, which, as you stated, is not what you want.
If you really want the effect, an alternative may be to prepend a separate element to the one you were giving the class, and fade in that element (with its background image).
The element would need to have absolute
positioning so that it doesn't affect the rest of the content.
You would end up with something like:
CSS:
li {
position: relative;
}
.background {
width: 100%;
height: 100%;
background:orange; // This would be your background image instead
position: absolute;
top: 0;
left: 0;
}
.content {
position: relative;
}
HTML:
<ul id='gallery'>
<li>
<div class='background'></div> // Prepend and fade in
<div class='content'>hi there</div>
</li>
</ul>
jQuery:
hover()
takes two functions. One when you mouseenter
, the other when you mouseleave
.
// Set opacity to 0 for all .background elements $('.background').css({opacity: 0});
var gallery = $('ul#gallery').children();
gallery.filter(':even').not(':last').hover(
function () {
$(this).find('.background').animate({'opacity': 1}, 500);
},
function () {
$(this).find('.background').animate({'opacity': 0}, 500);
});
EDIT:
FYI, you can change your selector to get what you want right away without having to call .filter()
, and so on.
var gallery = $('ul#gallery li:even:not(:last)');
gallery.hover(...
EDIT:
Changed wording in first sentence and added link to docs.
精彩评论