jQuery li with image fade in background (fade in class)

孤街浪徒 提交于 2019-12-14 03:58:43

问题


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 fade in the new class without making the image blink/fade at all?


回答1:


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.



来源:https://stackoverflow.com/questions/2851757/jquery-li-with-image-fade-in-background-fade-in-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!