html - 如何创建一个固定全屏不可滚动的div?

标签 html css

我正在尝试模仿典型的模式。当用户单击某些内容时,会显示模式,并带有全屏且固定的透明背景。

目前我有这个:

.thank-outer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: rgba(222, 222, 222, 0.7);
}
<div class="thank-outer" id="thankyou"> Some text </div>

div的高度不是浏览器的高度,而是整个页面内容的高度,因此它是可滚动的。

如何更改它以使div的高度恰好是浏览器的高度?

最佳答案

您可以通过将 body 元素的 overflow 属性设置为 hidden 轻松实现此目的。这会切断所有溢出屏幕的元素(并会形成滚动条)。

const $modal = document.querySelector('.modal');
const $button = document.querySelector('button');    

// Opening modal
$button.addEventListener('click', () => {
  document.body.classList.toggle('modal-visible');
  $modal.classList.toggle('visible');
});
body.modal-visibile {
  /* remove scroll bars when modal visible */
  overflow: hidden;
}

.modal {
  /* it is initially hidden */
  display: none;
  
  /* it will span whole screen */
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100vh;


  /* make it on top of all elements */
  z-index: 1000;
  overflow: hidden;
  pointer-events: all;
  
  /* make the background white, but also with 80% opacity */
  background: rgba(222, 222, 222, 0.8);
}

.modal.visible {
  display: block;
}
    
button {
  position: relative;
  z-index: 1001;
}
<button>Toggle Modal</button>

<h1>Some amazing content</h1>
<h2>Hopefully you enjoy this awesome content.</h2>
<p>Why are you still reading this? Just click the button!</p>

<div class="modal">
  <h1>It's a whole new world!</h1>
</div>

关于html - 如何创建一个固定全屏不可滚动的div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45023916/

相关文章:

javascript - JQuery Lightbox - 对不是链接的图像进行分组

html - 为什么我的 div 没有对齐到顶部?

css - 数据表搜索过滤器未与表格的最右侧部分对齐

CSS:绝对位置问题

python - .css 不会影响我在 django 中的模板

javascript - 自动表格布局和 colspan

jquery - 为什么IE8渲染superfish菜单错误?

css - @font-face 不起作用

html - 使 flex div 的宽度适应内容,但将 Flex 元素放在单独的行中

javascript - 如何在 angularjs 中隐藏和显示 HTML 元素?