javascript - 防止灯箱内部div被关闭

标签 javascript jquery html css

我正在制作一个在页面准备就绪时运行的简单灯箱。

但是,我想在灯箱内实现一个表单,这样如果用户点击较暗的部分(或关闭按钮),表单就会消失,但如果他点击白色部分(包裹表单)内的任何部分, 它防止被关闭。

目前我有以下内容:

$(document).ready(function() {
  // lightbox
  $('.widget').fadeIn(2000);
  $('.lightbox').click(function(e) {
    $(this).fadeOut();
  })
});
body {
  background-color: yellow;
  color: #fff;
}
.lightbox {
  display: table;
  position: fixed;
  overflow: hidden;
  z-index: 999;
  width: 100%;
  height: 100%;
  text-align: center;
  top: 0;
  left: 0;
  background: rgba(88, 73, 81, 0.85);
}
.widget-wrap {
  display: table-cell;
  vertical-align: middle;
  margin: auto;
  width: 300px;
  min-height: 300px;
}
.widget {
  display: none;
  margin: auto;
  width: 300px;
  height: 300px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="lightbox">
  <div class="widget-wrap">
    <div class="widget">
      <input type="text" placeholder="sample">
      <button>Subscribe</button>
    </div>
  </div>
</div>

最佳答案

您可以在 .widget 的事件处理程序中使用 return false。该事件不会冒泡到父元素,即 .lightbox 并且 lightbox 不会关闭。

$(document).ready(function() {
  // lightbox
  $('.widget').fadeIn(2000);
  $('.lightbox').click(function(e) {
    $(this).fadeOut();
  });

  // For preventing the bubbling of the event to the .widget event handler
  $('.widget').on('click', function() {
    return false;
  });
});
body {
  background-color: yellow;
  color: #fff;
}
.lightbox {
  display: table;
  position: fixed;
  overflow: hidden;
  z-index: 999;
  width: 100%;
  height: 100%;
  text-align: center;
  top: 0;
  left: 0;
  background: rgba(88, 73, 81, 0.85);
}
.widget-wrap {
  display: table-cell;
  vertical-align: middle;
  margin: auto;
  width: 300px;
  min-height: 300px;
}
.widget {
  display: none;
  margin: auto;
  width: 300px;
  height: 300px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="lightbox">
  <div class="widget-wrap">
    <div class="widget">
      <input type="text" placeholder="sample">
      <button>Subscribe</button>
    </div>
  </div>
</div>

关于javascript - 防止灯箱内部div被关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323539/

相关文章:

javascript - Angular Service 提供默认值吗?

javascript - 如何更改网站中的默认键盘快捷键

jquery - 使用 ajax 加载内容时在 Bootstrap 选项卡之间显示微调器

html - 使 NavItem 背景颜色与 NavBar 相同

javascript - 如何创建一个事件以在所有插件启动后触发?

javascript - 从对象列表中获取所有可能的对象键 Javascript/TypeScript

Javascript/谷歌地图 - 无法删除标记

javascript - Handsontable - 粘贴到单元格时禁用自动向上滚动

javascript - 使用单选按钮而不是链接单击的 jquery 选项卡

html - 如何自定义选择标签?