jQuery background-position animation

谁说我不能喝 提交于 2019-12-24 03:02:06

问题


I've created an image which is basically a CSS sprite of 3 images together. It's size is 278x123 so they are basically 3 images of 278x41.

What I am trying to do is to make an animation of that by changing the background position.

I've tried many things, one of my not very working solution is the following:

    var $slogan = $('#header h2 span');
$slogan.css({backgroundPosition: '0px 0px'});
function slogan_animation() {
    if ($slogan.css('background-position') == '0px 0px') {
        $slogan.fadeIn('slow').css('background-position', '0px -41px').fadeOut('slow');
    }
    else if ($slogan.css('background-position') == '0px -41px') {
        $slogan.fadeIn('slow').css('background-position', '0px -82px').fadeOut('slow');
    }
    else if ($slogan.css('background-position') == '0px -82px') {
        $slogan.fadeIn('slow').css('background-position', '0px 0px').fadeOut('slow');
    }
}
setInterval(slogan_animation, 2000);

Any ideas how could I do that?

Basically I just need to: - set my background position to "0px 0px", then move it to "0px -41px", then "0px -82px" and then loop it again from "0px 0px". It would be also great to have fadeIn() effect between those.

Any ideas?

Thank you.


回答1:


The background-position style is a composite style, so when you read it, it might not give the result that you expect. Also, the result may differ between browers.

Try using a variable to keep track of the position instead of reading it from the style. Set the position before you start the fade in:

$(function(){

  var $slogan = $('#header h2 span');
  var offset = 0;

  window.setInterval(function(){
    $slogan.css('background-position', '0 -'+offset+'px')
    .fadeIn('slow')
    .fadeOut('slow');
    offset = (offset + 41) % 123;
  }, 2000);

});


来源:https://stackoverflow.com/questions/3007180/jquery-background-position-animation

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