通过esc键或外部点击检测jquery显示插件模式关闭

Detect jquery reveal plugin modal close by esc key or clicking outside

本文关键字:显示 jquery 插件 模式 检测 esc 外部 通过      更新时间:2023-09-26

我正在使用jquery显示插件来显示弹出窗口。我正在jquery或javascript中寻找一种方法,当弹出窗口关闭时,我可以通过按下esc键或在弹出窗口外单击来触发适当的事件。有什么方法可以让我捕捉到这个事件吗?

在显示插件网站上,只给出了几个选项,比如:

$('#myModal').reveal({
 animation: 'fadeAndPop',                   //fade, fadeAndPop, none
 animationspeed: 300,                       //how fast animtions are
 closeonbackgroundclick: true,              //if you click background will modal close?
 dismissmodalclass: 'close-reveal-modal'    //the class of a button or element that will close an open modal
});

这个插件还有其他选项吗?如果是,请为我提供链接。

根据来源,在这两种情况下都会触发一个名为"show:close"的事件,您应该能够通过为该事件添加自己的处理程序

$yourModal.bind('reveal:close', function () {
  console.log('Modal closed');
});

当您需要知道它是以何种方式关闭的时,可以使用"show:open"事件在文档对象上添加keyup事件处理程序,或在.show-modalbg元素上添加click事件处理程序。

$yourModal.bind('reval:open', function () {
  var $document = $(document);
  $document.bind('keyup', function onEscHandler( event ) {
    if (event.which === 27) {
      console.log('closed by ESC');
      // Modal is closed, let's remove the handler again
      $document.unbind('keyup', onEscHandler);
    }
  });

  var $modal_bg = $('.reveal-modal-bg');
  $modal_bg.one('click', function onBgClidkHandler() {
    console.log('closed by click on BG');
    // We don't need to remove this handler since 'one' does it automatically.
  });
});
  1. 打开jquery.reveal.js

  2. 添加新选项:

    var defaults = {
    animation: 'fadeAndPop', animationspeed: 300, closeonbackgroundclick: true, dismissmodalclass: 'close-reveal-modal' escape: true // true: modal close with Esc. false: modal no close with Esc };

  3. 在文件jquery.validate中,找到包含e.which===27的行。

    完整的线路是:

    if(e.which===27){ modal.trigger('reveal:close'); }

  4. 修改并验证此行中的新选项escape

    if(e.which===27 && options.escape === true){ modal.trigger('reveal:close'); }

  5. 就是这样。现在escape选项起作用了。