我有一个对mousemove起反应的插件,如果我调用同一个插件的第二个实例,它就会编写第一个调用的绑定。如何创建可以使用不同设置的相同事件的插件?
(function($, document){
$.fn.parallax = function(options){
options = $.extend({
speed: .4,
speedY: .2,
random: false
}, options);
$this = this;
var cursor = {};
cursor.delta = {};
cursor.X = 0;
cursor.Y = 0;
$this.children().each(function(ind, layer) {
if (options.random) {
$(layer).data("speedX",Math.random()*options.speed);
$(layer).data("speedY",Math.random()*options.speedY);
};
})
$(document).mousemove(function(event) {
cursor.delta.X = $this.offset().left - cursor.X;
cursor.delta.Y = $this.offset().top - cursor.Y;
cursor.X = +event.pageX;
cursor.Y = +event.pageY;
$this.children().each(function(ind, layer) {
startX = +$(layer).css("left");
startY = +$(layer).css("top");
speedX = $(layer).data("speedX")?$(layer).data("speedX"):options.speed;
speedY = $(layer).data("speedY")?$(layer).data("speedY"):options.speedY;
$(layer).css({
transform : "translate("+ (cursor.delta.X*speedX) +"px, "+ (cursor.delta.Y*speedY) +"px)"
},100);
})
console.log($this);
});
return this;
};
})(jQuery, document);发布于 2014-08-21 11:11:12
问题就在这里:
$this = this;js创建了全局$this,并在第二次调用时重写了它。解决方案是var,它将创建本地$this,并相应地更改它们。
var $this = this; 更重要的是,您可以通过引入 mode来避免这类问题,这将在采取不安全的操作时抛出错误,例如访问全局对象。
https://stackoverflow.com/questions/25424085
复制相似问题