一个事件的两个插件实例

时间:2014-08-21 10:32:23

标签: jquery jquery-plugins

我有一个对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);

1 个答案:

答案 0 :(得分:0)

问题在这里:

$this = this;

js创建了全局$ this,并在第二次调用时覆盖了它。 解决方案是var,它将创建本地$ this,并相应地更改它们

var $this = this;  

你可以通过引入'use strict' mode来避免这类问题,当采取不安全的行动时会引发错误,例如获取对全局对象的访问权。

相关问题