所以我有这个 div,它包含一个表单,该表单的验证消息淡入淡出,改变了 div 的宽度和高度。我有一些 jQuery 使 div 居中,但我遇到的问题是当验证消息淡入并调整 div 大小时 jQuery 没有响应。
我需要一些代码来监听 div 的宽度和高度吗?
我目前的代码
resizeElement = '.blurHolder';
var holderHeight = jQuery(resizeElement).outerHeight();
var holderWidth = jQuery(resizeElement).outerWidth();
jQuery(resizeElement).css({
'margin-top': - holderHeight / 2,
'margin-left': - holderWidth / 2
});
有什么帮助吗?
最佳答案
试试这个:
html
<div class="container">
<div class="blurHolder"></div>
</div>
CSS
.container{
background: orange;
width: 400px;
height: 400px;
float: left;
margin: 10px;
}
.container .blurHolder{
width: 100px;
height: 100px;
background: #333;
}
js
$( document ).ready(function() {
var containerHeight = $('.container').height();
var containerWidth = $('.container').width();
var offsetTop = (containerHeight - $('.container').find('.blurHolder').height())/2;
var offsetLeft = (containerWidth - $('.container').find('.blurHolder').width())/2;
$('.container').css({'padding-top': offsetTop, 'padding-left': offsetLeft, 'height': containerHeight - offsetTop, 'width': containerWidth - offsetLeft});
});
关于javascript - 使用 jQuery 居中一个灵活的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21062195/