我会说我对 HTML 和 CSS 很在行,但当我开始接触 JavaScript 时,我却很吃力;我能理解其中的一些,但我一辈子都写不出来!不过,我正在努力学习,无论如何;我将这个 jQuery 脚本放在一起,目标是在相对定位的顶部 div 和绝对定位的底部 div 之间垂直居中放置一个 div。这不适合我,大声笑。
因为我正在尝试学习如何使用 jQuery 并创建我自己的脚本,所以我想尝试让它工作。但是,如果有更好的方法来实现我的目标,我也非常感谢您以这种方式提供的意见!
<script type="text/javascript">
$(document).ready(function() {
$(window).ready(function(){
vertical_height()
});
$(window).resize(function(){
vertical_height()
});
function vertical_height(){
var doc_height = $(document).height();
var head_height = $(".headcontent").height();
var mid_height = $(".midcontent").height();
var foot_height = $(".footer").height();
var pos_height = Math.round(head_height+foot_height);
var neg_height = Math.round((head_height-foot_height)/2);
var fin_height = Math.round(doc_height-(pos_height-neg_height));
$('.midcontent').css({
"marginTop","-"+fin_height+"px",
"marginBottom","-"+fin_height+"px"
}
}
});
</script>
.headcontent 是最上面的 div。
.midcontent 是我想要居中的中间 div。
.footer 是底部的 div。
最佳答案
这是你的代码,整理成可以运行的东西:
$(function() {
function vertical_height() {
var doc_height = $(document).height();
var head_height = $(".headcontent").height();
//var mid_height = $(".midcontent").height();//not used
var foot_height = $(".footer").height();
var pos_height = head_height + foot_height;
var neg_height = (head_height - foot_height) / 2;
var fin_height = doc_height - (pos_height - neg_height);
$('.midcontent').css({
"marginTop": "-" + fin_height + "px",
"marginBottom": "-" + fin_height + "px"
});
}
$(window).resize(vertical_height).trigger('resize');
});
现在您可以专注于使算法正确。
就目前而言,组合和简化表达式,我得到:
var fin_height = doc_height - head_height*3/2 - foot_height*3/2;
这对我来说不对,但我可能是错的。
编辑
为了避免重叠,试试这个版本:
var $$ = {}; //jQuery object cache.
$$.w = $(window);
$$.h = $(".headcontent");
$$.m = $(".midcontent");
$$.f = $(".footer");
function vertical_height() {
var w = $$.w.height(),
h = $$.h.outerHeight(true),
m = $$.m.outerHeight(),
f = $$.f.outerHeight(true),
fin_height = Math.max(0, (w - h - m - f) / 2);
$$.m.css('marginTop', Math.floor(fin_height)).css('marginBottom', Math.ceil(fin_height));
$$.h.text(fin_height);
};
$(window).on('resize', vertical_height).trigger('resize');
注释
position:absolute
从页脚的 CSS 中移除- jQuery 对象现在缓存在
$$
中,以减少调整大小处理程序要做的工作。 - 现在基于窗口高度而不是文档高度进行计算。
- 现在用
.outerHeight(false)
测量三个 div,以包括垂直填充和边框。 Math.max(0, ...)
可防止重叠,从而确保翅片高度不会为负数。$$.h.text(fin_height);
语句用于调试,可以去掉。
编辑2
以下代码将“去抖动”调整大小事件。
替换:
$(window).on('resize', vertical_height).trigger('resize');
与:
var do_resize;
$(window).on('resize', function(){
clearTimeout(do_resize);
do_resize = setTimeout(vertical_height, 100);
}).trigger('resize');
关于javascript - 如何使一个div在两个div之间垂直居中?查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787509/