开发者

Help applying a fade to background-position change with Jquery

开发者 https://www.devze.com 2023-01-09 20:53 出处:网络
I\'m very new to Jquery but have finally worked out how to change the background-image (a sprite开发者_JAVA技巧) of my #contentContainer when hovering over a separate \'trigger\' image. However, for t

I'm very new to Jquery but have finally worked out how to change the background-image (a sprite开发者_JAVA技巧) of my #contentContainer when hovering over a separate 'trigger' image. However, for the life of me I cannot work out how to apply a fade effect to the transition. Basically, instead of the current abrupt background image transition I would like it to fade in smoothly on mouseover and mouseout.

Here is my (non fading but working) script:

var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#swapTrigger").hover(
function() {
$j("#contentContainer").css("background-position", "0px 1401px");    
},
function() {
$j("#contentContainer").css("background-position", "0px 0px");  
});
});

Very many thanks for any help!


Try using http://api.jquery.com/animate

 $j("#contentContainer").animate({"background-position": "0px 1401px"}, "slow");


You can animate the background position property, which will give you a smooth transition between the 2 images:

$j("#swapTrigger").css({backgroundPosition: "0 0"}); 
$j("#swapTrigger").hover(
    function() {
        $j("#contentContainer").animate({backgroundPosition: "0 1401px"});    
    },
    function() {
        $j("#contentContainer").animate({backgroundPosition: "0 0"});  
    }
);

If your question is about fading the opacity of the images as they switch between the 2, you can't do it with a single element. You'll need to add your background image to nested elements and then fade them in and out:

<div id="contentContainer">
    Some content
    <div class="bg1"></div>
    <div class="bg2"></div>
</div>

On hover, fade them in and out as required:

var bg1 = $('.bg1');
var bg2 = $('.bg2');
$j("#swapTrigger").hover(
    function() {
        if(bg1.is(':hidden')){
           bg1.stop().fadeIn();
           bg2.stop().fadeOut();
        } else {
           bg2.stop().fadeIn();
           bg1.stop().fadeOut();
        }   
    }
);
0

精彩评论

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

关注公众号