问题描述
我正在尝试创建一个简单的模态弹出窗口。我已经完成了CSS,并且Javascript主要完成了。我点击页面按钮上的按钮,弹出窗口,但它出现在页面顶部。如果你一直滚动到页面顶部,它会显得如此。
I'm trying to create a simple modal popup. I have the CSS done, and the Javascript mostly done. I'm at the point where I click a button at the button of the page and the popup appears, but it appears at the top of the page. It appears excatly how it should if you were scrolled all the way to the top of the page.
我希望模态弹出框根据当前滚动显示为中心位置。当我滚动时,我也希望它保持居中。截至目前,它不会浮动在屏幕的中心。
I however want the modal popup box to appear center based upon the current scroll position. I also want it to stay centered when I scroll. As of right now it doesn't float at the center of the screen.
当我滚动时,我需要使用什么javascript属性来调整弹出div的位置。
What javascript property do I need to use to adjust the position of the popup div as I scroll.
我试过了,但无济于事:
I've tried, but to no avail:
function showModal(id)
{
window.onscroll = function () { document.getElementById(divID).style.top =
window.pageYOffset ||
document.body.scrollTop ||
document.documentElement.scrollTop; };
document.getElementById(id).style.display = "block";
document.getElementById(id).style.top =
window.pageYOffset ||
document.body.scrollTop ||
document.documentElement.scrollTop; };
}
我正在使用直接的vanilla javascript,没有jQuery。
I'm using straight vanilla javascript, no jQuery.
TL; DR:我创建了一个模态弹出框,但当我从页面顶部滚动时它不会保持居中。
TL;DR: I've created a modal popup but it doesn't stay centered when I scroll away from the very top of the page.
推荐答案
尝试 position:fixed
为你的css,它不会用这个滚动,也检查
try position: fixed
for your css, it won't scroll with this, also check display HTML page after loading complete
示例:
<style>
#floater {float:left; height:50%; margin-bottom:-1px;}
#top {position: fixed; top:0; left: 0; width: 100%; height: 100%; background: #fff}
#content {clear:both; height:540px; position:relative; height: 100%; width: 100%;}
</style>
<div id="top">
<div id="floater"></div>
<div id="content">
<div style="border: 1px solid #DDD; padding: 10px; background: #BBB; width: 300px; margin: 0 auto">Popup Contents Here</div>
</div>
</top>
-
#top
元素使隐藏背景,你可以使它透明但仍然无法点击。 -
#floater
和#content
适用于。 #top
element makes hides background, you can make it transparent but still unclickable.#floater
and#content
are for vertical centering.
这篇关于Javascript模态弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!