Vla*_*dod 9 html javascript css jquery twitter-bootstrap
如何将模态居中到屏幕中心?这是我的html和js代码它适用于Chrome控制台,但是当我刷新此页面时 - 它不起作用
$('.modal').css('top', $(window).outerHeight() / 2 - ($(".modal-dialog").outerHeight()) / 2 + 'px');
Run Code Online (Sandbox Code Playgroud)
Vla*_*dod 15
简单的解决方法
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
xxx*_*tko 10
没有必要使用jQuery,只需使用css即可实现:
body {
background: gray;
}
.modal {
background: green;
position: absolute;
float: left;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}Run Code Online (Sandbox Code Playgroud)
<div class="modal">
Lorem ipsum
</div>Run Code Online (Sandbox Code Playgroud)
如果您更喜欢jQuery解决方案,请访问:
$(function() {
var modal = $(".modal");
var body = $(window);
// Get modal size
var w = modal.width();
var h = modal.height();
// Get window size
var bw = body.width();
var bh = body.height();
// Update the css and center the modal on screen
modal.css({
"position": "absolute",
"top": ((bh - h) / 2) + "px",
"left": ((bw - w) / 2) + "px"
})
});Run Code Online (Sandbox Code Playgroud)
body {
background: gray;
}
.modal {
background: green;
float: left;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal">
Lorem ipsum
</div>Run Code Online (Sandbox Code Playgroud)
小智 8
如果您使用 Bootstrap 模态,您所需要做的就是将 .modal-dialog-centered 类添加到模态对话框中。见下文
改变这一行<div class="modal-dialog" role="document">
到这一行<div class="modal-dialog modal-dialog-centered" role="document">
小智 5
像这样尝试
.modal {
text-align: center;
padding: 0!important;
}
.modal:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px;
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)
如果你更喜欢 jquery 意味着试试这个
function setModalMaxHeight(element) {
this.$element = $(element);
this.$content = this.$element.find('.modal-content');
var borderWidth = this.$content.outerHeight() - this.$content.innerHeight();
var dialogMargin = $(window).width() < 768 ? 20 : 60;
var contentHeight = $(window).height() - (dialogMargin + borderWidth);
var headerHeight = this.$element.find('.modal-header').outerHeight() || 0;
var footerHeight = this.$element.find('.modal-footer').outerHeight() || 0;
var maxHeight = contentHeight - (headerHeight + footerHeight);
this.$content.css({
'overflow': 'hidden'
});
this.$element
.find('.modal-body').css({
'max-height': maxHeight,
'overflow-y': 'auto'
});
}
$('.modal').on('show.bs.modal', function() {
$(this).show();
setModalMaxHeight(this);
});
$(window).resize(function() {
if ($('.modal.in').length != 0) {
setModalMaxHeight($('.modal.in'));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35979 次 |
| 最近记录: |