在模态 div 内滚动而不滚动整个页面

Scrolling within modal div without scrolling the entire page

我有一个包含一些内容的网页。然后我弹出一个模式。

我遇到的问题是,当我尝试滚动模式中的内容时,只有滚动后面的内容。

这是CSS:

html, body {
    background: blue;
    margin: 0px;
}

/* Content Behind */
.content {
    width: 100%;
    background: red;
    z-index: 100;
}

/* Modal Above */
#modal {
    background: yellow;
    position: fixed;
    top: 10px;
    left: 50%;
    width: 400px;
    transform: translateX(-50%);
    z-index: 200;
    overflow: scroll;
    display: none;
    padding: 5px;
}

.show {
    display: block !important;
}

See Fiddle

谢谢

您没有为模态框设置固定高度。

试试这个:

#modal {
    background: yellow;
    position: fixed;
    top: 10px;
    left: 50%;
    width: 400px;
    height: 400px; // Here you set the height of your choice
    transform: translateX(-50%);
    z-index: 200;
    overflow: scroll;
    display: none;
    padding: 5px;
}

Working fiddle

看到这个fiddle

您还没有为 #modal 指定身高。更新您的 CSS 如下

#modal {
    background: yellow;
    position: fixed;
    top: 10px;
    left: 50%;
    width: 400px;
    height:100%;     /*<<<<<<<<<specify height>>>>>>>>*/
    transform: translateX(-50%);
    z-index: 200;
    overflow: scroll;
    display: none;
    padding: 5px;
}

更新

为了防止模式打开时后面的内容滚动,你必须稍微改变一下你的Javascript。

请查看更新后的 fiddle

修改后的JS如下

var bodyElems = document.getElementsByTagName("body");
var body = bodyElems[0];
body.style.overflow = "hidden";

document.getElementById('openModal').onclick = function () {
    document.getElementById("modal").className = "show";
    body.style.overflow = "hidden";

};

document.getElementById('closeModal').onclick = function () {
    document.getElementById("modal").className = "";
    body.style.overflow = "auto";
};