我正在尝试在 div 中水平和垂直居中模式窗口。我希望它是跨浏览器兼容的。您可以从下图中看到,当我调整 IE8 的大小然后单击“显示模式”按钮时,它显示的不是完全水平居中。这似乎不是 Chrome 的问题。有什么想法吗?你们将如何实现这一目标?
<html>
<head>
<title>test</title>
<style type="text/css">
*
{
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#modal').click(function() {
// overlay
$('<div id="overlay" />').css({
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: 'black',
opacity: 0
}).appendTo('body');
$('<div id="datamodal" />').css({
backgroundColor: '#FFFFFF',
border: '10px solid #999',
height: '200px',
width: '600px',
position: 'absolute',
top: '50%',
left: '50%',
marginTop: '-120px',
marginLeft: '-320px',
color: '#111111',
fontWeight: 'bold',
padding: '10px',
display: 'none'
}).append('<input type="text" />').appendTo('#overlay');
$('#overlay').fadeTo(300, 0.7);
$('#datamodal').fadeIn(300);
});
});
</script>
</head>
<body>
<input id="modal" type="button" value="show modal" />
</body>
</html>
最佳答案
您需要根据窗口和对话框的大小计算位置,并通过 JavaScript 设置样式。
示例来自:Using jQuery to center a DIV on the screen
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
关于jquery - 水平和垂直中心模态 Div IE 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632746/