I want to get the end position of my object. So the top and left position when the animation is done. I want to get that position directly not after the animation is finished.
I want to do this Object Oriented.
This is what i got:
(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);
When i make a block with this Class and console.log the position, then i get the position of the starting point of the block. I want to get the end position. Directly
var block1 = new Block
block1.appendTo('body')
.setSize(100,50)
.setPosition(200, 300, 3000);
console.log(block1.getPosition());
So console.log = [0, 0]
i want it to be [200, 300]
You can use data()
to store data related to the element:
(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);
You only can store the designated position when calling setPosition
, and retrieve that instead.
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];
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.