为多个 jquery 元素转换脚本

Convert script for multiple jquery elements

我以前用过这个脚本,只要我只需要一个覆盖就可以正常工作...... 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);
  });
});

您可以为多个元素定义多个点击处理程序。您只需要稍微改进一下 document.ready(),您不需要 return 任何东西。

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);
      });

    });

});