我正在使用这个脚本水平和垂直居中我的div.
当页面加载时,div会垂直居中,而不是水平居中,直到我调整浏览器大小.
我究竟做错了什么?
$(document).ready(function (){
$(window).resize(function (){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
$(window).resize();
});
Run Code Online (Sandbox Code Playgroud)
Dim*_*13i 61
我通常使用这种"技术":
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').width()/2,
'margin-top' : -$('.className').height()/2
});
});
Run Code Online (Sandbox Code Playgroud)
更新:
我正在按照用户Fred K的建议更新解决方案,使用.outerWidth()并.outerHeight()获得更精确的居中.
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : -$('.className').outerWidth()/2,
'margin-top' : -$('.className').outerHeight()/2
});
});
Run Code Online (Sandbox Code Playgroud)
来自jQuery文档(.outerWidth(),.outerHeight())的一些补充说明:
维度相关API返回的数字(包括.outerWidth())在某些情况下可能是小数.代码不应该假设它是一个整数.此外,当用户缩放页面时,尺寸可能不正确; 浏览器不公开API来检测这种情况.
当隐藏元素的父级时,.outerWidth()报告的值不保证是准确的.要获得准确的值,您应该在使用.outerWidth()之前首先显示父级.
更新2:
一个简单的更新,显示如何在具有不同大小的相同标记的更多元素的情况下this在css()方法内部使用class.
$(function() {
$('.className').css({
'position' : 'absolute',
'left' : '50%',
'top' : '50%',
'margin-left' : function() {return -$(this).outerWidth()/2},
'margin-top' : function() {return -$(this).outerHeight()/2}
});
});
Run Code Online (Sandbox Code Playgroud)
Jai*_*Jai 20
用这个来集中:
$.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2 + "px");
this.css("left", ( $(window).width() - this.width() ) / 2 + "px");
return this;
}
$('yourElem').center();
Run Code Online (Sandbox Code Playgroud)
cha*_*tfl 10
将处理程序代码包装在一个函数中,这样您就可以在页面加载和处理程序上调用该函数 $(window).resize()
/* use as handler for resize*/
$(window).resize(adjustLayout);
/* call function in ready handler*/
$(document).ready(function(){
adjustLayout();
/* your other page load code here*/
})
function adjustLayout(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
}
Run Code Online (Sandbox Code Playgroud)