在同一个元素上重叠jQuery插件

时间:2017-02-02 05:37:13

标签: javascript jquery

我编写了自己的jQuery插件,但我希望允许用户覆盖现有的设置。目前,如果您尝试这样做,浏览器会在单个元素上运行两个 jQuery插件实例。是的...我不知道如何测试,或者在控制台中显示它,甚至不知道如何解决这个问题。

提前感谢您的帮助!!

以下是问题的正常工作示例JS FIDDLE

// my innovative jquery pluggin!
$.fn.blink = function(options) {

    // basic setup
    var defaults = {blinkInterval: 3000}
    var settings = $.extend({}, defaults, options);
    var $box = $(this),
        delay = settings.blinkInterval;

    // hide box, then show after half the time has passed
    function blinkFunction(){
        $box.hide();
        setTimeout(function(){$box.show();}, delay/2)
    }

    // start blinking, set interval of full time provided
    setInterval(blinkFunction, delay);
};

// now use my pluggin!
$('#box').blink({blinkInterval:2000}); // blink every two seconds
$('#box').blink({blinkInterval:3000}); // blink every three seconds

// the goal is for this 3 second instance to over-write the 2 second one, because it was called later on. But unfortunately, right now it blinks every 2 seconds AND every 3 seconds!!! Sometimes they line up, and sometimes they don't... :(

1 个答案:

答案 0 :(得分:0)

更新为该特定元素指定的间隔和超时:

var $blink_timeout = [],
  $blink_interval = [];
// my innovative jquery pluggin!
$.fn.blink = function(options) {
  // basic setup
  var defaults = {
    blinkInterval: 3000
  }
  var settings = $.extend({}, defaults, options);
  var $box = $(this),
    delay = settings.blinkInterval,
    $id = $(this).attr("id");

  //alert($id);
  clearTimeouts();

  // hide box, then show after half the time has passed
  function blinkFunction() {
    $box.hide();
    $blink_timeout[$id] = setTimeout(function() {
      $box.show();
    }, delay / 2)
  };

  // start blinking, set interval of full time provided
  $blink_interval[$id] = setInterval(blinkFunction, delay);

  function clearTimeouts() {
    //clearTimeouts
    clearTimeout($blink_timeout[$id]);
    clearInterval($blink_interval[$id]);
  };
};

// now use my pluggin!
$('#box').blink({
  blinkInterval: 2000
}); // blink every two seconds
$('#box').blink({
  blinkInterval: 5000
}); // blink every three seconds
$('#box2').blink({
  blinkInterval: 2000
});

// the goal is for this 3 second instance to over-write the 2 second one, because it was called later on. But unfortunately, right now it blinks every 2 seconds AND every 3 seconds!!! Sometimes they line up, and sometimes they don't... :(
#box {
  height: 100px;
  width: 100px;
  background-color: red;
 
}

#box2 {
  height: 100px;
  width: 100px;
  background-color: green;
  position: absolute;
  top: 110px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<p>Watch me blink!</p>
<div id="box"></div>
<div id="box2"></div>