animate backgroundPosition

2019-07-27 04:09发布

问题:

Anyone know why the below would not work. If I just set the css directly without animate it works. //div.css( {backgroundPosition: "bottom left"} );

   $("#menu li").bind("mouseover", function(){
        var div=$(this).find('div');
        div.css( {backgroundPosition: "bottom left"} );
        div.stop().animate( {backgroundPosition: '25px 0px'}, {duration:500} );
    })
    .mouseout(function(){
        var div=$(this).find('div');
        div.stop().animate( {backgroundPosition: "0px 0px"}, {duration:500} );

    });

回答1:

you have to set the initial value of the backgroundPosition in IE otherwise this wont work because it doesn't know how to animate.

also i would change the mouseover and mouseout to have the same style not using bind onone and using the mouseover on the other like in my example

like this:

$("#menu li > div").css({
    backgroundPosition: "0px 0px"
})

$("#menu li").mouseover(function() {
    var div = $(this).find('div');
    div.stop().animate({
        backgroundPosition: '25px 0px'
    }, 500);
}).mouseout(function() {
    var div = $(this).find('div');
    div.stop().animate({
        backgroundPosition: "0px 0px"
    }, 500);
});


回答2:

Try this

$("#menu li").bind("mouseover", function(){
        var div=$(this).find('div');
        div.stop().animate( {backgroundPosition: '25px 0px'}, 500 );
    })
    .mouseout(function(){
        var div=$(this).find('div');
        div.stop().animate( {backgroundPosition: "0px 0px"}, 500 );

    });