我正在制作一个动画,每个列表项将在其包装器内随机浮动。我试着用原型继承模式组合在一起,但它没有这样做。我认为有几个地方可能是导致问题的原因,但我需要一些建议来继续进行。
function Menu($item) {
this.item = $item;
};
Menu.prototype.makeNewPosition = function ($container) {
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
};
Menu.prototype.move = function () {
$.each(this.item, function(index, value) {
var newq = this.makeNewPosition(value.parent());
value.animate({
top: newq[0],
left: newq[1]
}, 400, function() {
this.move();
});
});
};
var $menu = new Menu($('.nav li'));
$menu.move();
在move
函数中,有animate
,在这个函数中,我再次调用move
来无限期地运行动画。如果在原型结构中调用自己,可以用this
来调用吗?
不确定$.each
在move
函数中的使用。
这是一个更简洁的版本
- 使用self代替-我使用
that
,大多数人使用self
-我不同:p - set
$value = $(value)
…干
.
function Menu($item) {
this.item = $item;
};
Menu.prototype.makeNewPosition = function ($container) {
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
};
Menu.prototype.move = function () {
var self = this;
$.each(this.item, function(index, value) {
var $value = $(value);
var newq = self.makeNewPosition($value.parent());
$value.animate({
top: newq[0],
left: newq[1]
}, 400, function() {
self.move();
});
});
};
var $menu = new Menu($('.nav li'));
$menu.move();
这里是所有的错误修复,而不仅仅是第一个下面的原始答案-包含更改的解释
function Menu($item) {
this.item = $item;
};
Menu.prototype.makeNewPosition = function ($container) {
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
};
Menu.prototype.move = function () {
var that = this; // added that because the this isn't the this you want in the $.each function
$.each(this.item, function(index, value) {
var newq = that.makeNewPosition($(value).parent());
// ^^^^ ^^ ^
// that instead of this
// $(value) instead of value
$(value).animate({
// ^^ ^
// $(value) instead of value
top: newq[0],
left: newq[1]
}, 400, function() {
that.move();
//^^^^ another this to that change
});
});
};
var $menu = new Menu($('.nav li'));
$menu.move();
有更多的方法来清理代码,但这些更改应该至少使您能够工作
小提琴的工作变化http://jsfiddle.net/wzmh63xb/16/
这是你的错误。试试这个。
Menu.prototype.move = function () {
var self = this;
$.each(this.item, function(index, value) {
var newq = self.makeNewPosition($(value).parent());
$(value).animate({
top: newq[0],
left: newq[1]
}, 400, function() {
self.move();
});
});
};
演示