如果父's的高度div高于X,则显示此div



我试图在另一个div中显示一个div,如果父对象的高度大于,比如650px:

<div class="parent">
<div class="child>this need to be showed if parent's height is greater than 650px</div>
</div>

有什么方法可以用CSS来做吗?在问之前我找了很多。

edit:也接受CSS以外的其他解决方案,但我想知道这是否可能。

谢谢!

我知道你要求一个只使用CSS的方法,但你的问题被标记为javascript,所以你得到了一个javascript解决方案:

HTML:

<div id="parent">
<div id="child">This needs to be shown if parent has a height greater than 650px</div>
</div>

Javascript:

function checkHeight() {
var parentHeight = document.getElementById('parent').clientHeight;
if (parentHeight > 650) {
document.getElementById('child').style.display = "block";
} else {
document.getElementById('child').style.display = "none";
}
}

Element.clientHeight用于获取元素高度,包括填充,但不包括水平滚动条高度、边框或边距在MDN文档中阅读更多信息

每当您想检查parent的高度时,调用函数checkHeight()

更新:如果您正在使用类:请参阅此JSFiddle

这可以使用JQuery和height()方法轻松完成。我为您的.child添加了一个ID,以便我们可以使用document.getElementByIddisplay:blockdisplay:none

尝试以下操作:(只需将父高度值更改为高于650px和低于650px即可进行测试。(

var parent = $(".parent").height();
if (parent>650) {
	document.getElementById("child").style.display = "block";
}
#child {
display: none;
}
.parent {
height: 651px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="child" id="child">this need to be showed if parent is greater than 650px</div>
</div>

注意:父级的高度css纯粹用于测试目的,以查看此代码是否有效。测试后,您可以删除该代码,并让父类的自然高度在那里。它在摘录之前的括号中说明。

一个连续监控父对象高度的Javascript解决方案。因此,如果您通过Ajax将任何其他元素插入父元素,那么一旦达到设置的高度限制,就会显示子元素。

const parent = document.getElementsByClassName("parent")[0];
const child = document.getElementsByClassName("child")[0];
document.addEventListener("resize", checkParent);
let lastHeight = 0;
/* 
The button and #demo are for demonstration purpose only
*/
const demo = document.getElementById("demo");
const button = document.getElementsByTagName("button")[0];
button.onclick = () => demo.style.height = "101px";
function checkParent() {
const parentHeight = parent.clientHeight;
/* 
For the sake of example a height of 100 is used
This can obviously be set to any desired value
*/
if (parentHeight >= 100) child.style.display = "block";
}
/* 
Monitor the height of parent continuously
*/
function checkForChanges() {
const parentHeight = parent.clientHeight;
if (parentHeight != lastHeight) {
checkParent();
lastHeight = parentHeight;
}
setTimeout(checkForChanges, 500);
}
checkForChanges();
.child {
display: none;
}
<div class="parent">
<div class="child">this need to be showed if parent's height is greater than 100px</div>
<!-- demo is only used to demonstrate the functionality -->
<div id="demo"></div>
<button>Click me</button>
</div>