JQuery Animate Background Image on Y-axis

前端 未结 2 1702
無奈伤痛
無奈伤痛 2020-11-30 08:31

I seem to experiencing a problem with the JQuery animation. I can animate the background image in the positive direction, but not in the negative direction. Any suggestions

相关标签:
2条回答
  • 2020-11-30 08:57

    Positioning the background via separate background-position-x/y is a feature that Internet Explorer introduced but never made it into a W3C specification. Any recommendations to add it to the spec have since been denied.

    See: http://snook.ca/archives/html_and_css/background-position-x-y

    You can always create your own little plugin, it's not that hard.

    Using jQuery 1.8 we now have access to the $.Animation method that gives us the animated values directly without to much work, so we can do something like :

    $.fn.animateBG = function(x, y, speed) {
        var pos = this.css('background-position').split(' ');
        this.x = pos[0] || 0,
        this.y = pos[1] || 0;
        $.Animation( this, {
            x: x,
            y: y
          }, { 
            duration: speed
          }).progress(function(e) {
              this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px');
        });
        return this;
    }
    

    And then to use it we can do:

    $("#background").animateBG(x-value, y-value, speed);​
    

    FIDDLE

    This is something I whipped up for another answer some days ago, and only works with pixels and does have some limitations, but it's simple and should work for most cases.

    I guess something like this would do what you want:

    $(this).parent()
           .css('background-position', '0 19px');
           .animateBG(0, 0, 1000);​
    
    0 讨论(0)
  • 2020-11-30 08:58

    @adeneo: this solution only works if you set

    this.x = pos[0].split('px')[0] || 0;
    this.y = pos[1].split('px')[0] || 0;
    

    Otherwise the starting position will be set to zero.

    0 讨论(0)
提交回复
热议问题