转换多个jquery元素的脚本

时间:2015-01-27 16:14:53

标签: javascript jquery arrays methods

之前我已经使用过此脚本,只要我只需要一个叠加层就能正常使用... https://gist.github.com/jamesotron/8fa41dd9e9ab2c78e9f0

现在我需要在多个可点击元素上调用它。 每个人应该打开一个不同的叠加层。 当用户点击#second-overlay,#third-overlay等时,我如何重构它以传递多个#div-second,#div-third等?

谢谢。

var Overlay, onEndTransition, supportsTransitions, transitionEndEventName;

transitionEndEventName = function() {
  var transEndEventNames;
  transEndEventNames = {
    WebkitTransition: "webkitTransitionEnd",
    MozTransition: "transitionend",
    OTransition: "oTransitionEnd",
    msTransition: "MSTransitionEnd",
    transition: "transitionend"
  };
  return transEndEventNames[Modernizr.prefixed("transition")];
};

supportsTransitions = function() {
  return Modernizr.csstransitions;
};

onEndTransition = function(ev) {
  if (supportsTransitions()) {
    if (ev.propertyName !== "visibility") {
      return;
    }
    this.overlay.off(transitionEndEventName(), onEndTransition);
  }
  return this.overlay.removeClass('close');
};

Overlay = (function() {
  function Overlay(overlay) {
    var closeButton;
    this.overlay = overlay;
    closeButton = this.overlay.find('button.overlay-close');
    if (closeButton.length > 0) {
      closeButton.click((function(_this) {
        return function(e) {
          return _this.toggle(e);
        };
      })(this));
    }
  }

  Overlay.prototype.isOpen = function() {
    return this.overlay.hasClass('open');
  };

  Overlay.prototype.close = function() {
    this.overlay.removeClass('open');
    this.overlay.addClass('close');
    if (supportsTransitions()) {
      return this.overlay.on(transitionEndEventName(), (function(_this) {
        return function() {
          return onEndTransition.call(_this);
        };
      })(this));
    } else {
      return onEndTransition.call(this);
    }
  };

  Overlay.prototype.open = function() {
    return this.overlay.addClass('open');
  };

  Overlay.prototype.toggle = function(e) {
    if (this.isOpen()) {
      return this.close();
    } else {
      return this.open();
    }
  };

  return Overlay;

})();

$(document).ready(function() {
  var overlay;
  overlay = new Overlay($('div.first'));
  return $('#first-overlay').click(function(e) {
    return overlay.toggle(e);
  });
});

1 个答案:

答案 0 :(得分:1)

您可以为多个元素定义多个点击处理程序。你只需要优化你的document.ready()一点,你不必返回任何东西。

var mappings = {
  '#first-overlay' : '#div-first',
  '#second-overlay' : '#div-second',
  '#third-overlay' : '#div-third'
};

$(document).ready(function() {

    $.each( mappings, function( key, val ) {
       /* create a new overlay object and use click handler just to toggle  */
       var Overlay = new Overlay($(value));
       $(key).on('click',function(e) {
        overlay.toggle(e);
      });

    });

});