学习记录
position: absolute 会脱离文档流,其对应的父元素不会随着子元素的内容自动撑开。想要子元素靠右对齐或者居中对齐,同时做自适应的效果,用jquery获取每个子元素的高度再给父元素。
jquery 部分
$('.abH').each(function(){
// 为每个class="abH"的盒子执行函数
var abHeight = $(this).innerHeight();
$(this).parent().innerHeight(abHeight);
// innerHeight() 返回元素的高度(包含 padding,不包含 border)
// height() 返回元素的高度(不包含 padding)
$(window).resize(function(){
// 窗口重置时要重新获取每个class="abH"盒子的高度
$('.abH').each(function(){
var abHeight = $(this).innerHeight();
$(this).parent().innerHeight(abHeight);
})
});
});
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>父元素获取绝对定位子元素的高度</title>
<style>
.test-content{
background: #f2f2f2;
}
.pos-center{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.pos-ri{
position: absolute;
right: 0;
top: 0;
}
.abH-box{
position: relative;
margin: 50px 0;
background: #ccc;
}
h4{
font-size: 5vw;
}
.normal{
background: #aaa;
}
</style>
</head>
<body>
<div class="test-content">
<div class="abH-box">
<div class="abH pos-center">
<h4>绝对定位居中对齐</h4>
</div>
</div>
<div class="abH-box">
<div class="abH pos-ri">
<h4>绝对定位靠右对齐</h4>
</div>
</div>
<div class="normal">
<h4>正常盒子</h4>
</div>
</div>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(function(){
$('.abH').each(function(){
var abHeight = $(this).innerHeight();
$(this).parent().innerHeight(abHeight);
$(window).resize(function(){
$('.abH').each(function(){
var abHeight = $(this).innerHeight();
$(this).parent().innerHeight(abHeight);
})
})
})
})
</script>
</body>
</html>
版权声明:本文为nicholeni原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。