【问题标题】:Get end position of element. The position when the animation is finished. In OOP Javascript/jQuery获取元素的结束位置。动画结束时的位置。在 OOP Javascript/jQuery 中
【发布时间】:2012-12-01 10:06:25
【问题描述】:

我想得到我的对象的结束位置。所以动画完成时的顶部和左侧位置。我想在动画完成后直接获得那个位置。

我想做这个面向对象的。

这是我得到的:

(function($) {

    Block = function() {

        this.el = $('<div></div>');
        this.el.css('position', 'relative');

        }

    Block.prototype.appendTo = function(parent) {

         this.el.appendTo(parent);
         return this;
    }

    Block.prototype.setSize = function(w, h) {

         this.el.css('width', w); 
         this.el.css('height', h);
         return this;    
    }

    Block.prototype.setPosition = function(x, y, speed) {

        speed = speed || 0;
        this.el.animate({'left': x+ 'px', 'top': y+ 'px'}, speed);
        return this;
    }

    Block.prototype.getPosition = function() {

        var left = this.el.position().left;
    var top = this.el.position().top;
    return [left, top];
    }



})(jQuery);

当我用这个类和console.log创建一个块时,我得到了块起点的位置。我想获得最终位置。直接

var block1 = new Block
block1.appendTo('body')
        .setSize(100,50)
        .setPosition(200, 300, 3000);


console.log(block1.getPosition());

所以 console.log = [0, 0] 我希望它是 [200, 300]

【问题讨论】:

  • 您为什么要这样做?只需获取动画后的位置即可。

标签: javascript jquery jquery-animate position


【解决方案1】:

您可以使用data()来存储与元素相关的数据:

(function($) {
    Block = function() {
        this.el = $('<div></div>');
        this.el.css('position', 'relative');
    }

    Block.prototype.appendTo = function(parent) {
         this.el.appendTo(parent);
         return this;
    }

    Block.prototype.setSize = function(w, h) {
         this.el.css({width: w, height: h}); 
         return this;    
    }

    Block.prototype.setPosition = function(x, y, speed) {
        speed = speed || 0;
        this.el.data({top: y, left: x}).animate({'left': x+ 'px', 'top': y+ 'px'}, speed);     return this;
    }

    Block.prototype.getPosition = function() {
        return [this.el.data('left'), this.el.data('top')];
    }
})(jQuery);

FIDDLE

【讨论】:

    【解决方案2】:

    您只能在调用setPosition时存储指定的位置,然后取而代之。

    Block = function() {
        this.el = $('<div></div>').css('position', 'relative');
        this.position = null;
    };
    Block.prototype.setPosition = function(x, y, speed) {
        this.position = {'left': x, 'top': y};
        this.el.animate(this.position, speed || 0);
        return this;
    };
    Block.prototype.getPosition = function() {
        var pos = this.position || this.el.position();
        return [pos.left, pos.top];
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多