我有以下代码:
<h3 class="hideIfDivEmpty">title</h3>
<div id="divId"></div>
当 div 为空时,我想隐藏 h3 元素。我愿意更改 html 结构,但 h3 必须在 div 之外,因为它的内容是动态更改的。
有没有办法在 CSS 中做到这一点?
我有以下代码:
<h3 class="hideIfDivEmpty">title</h3>
<div id="divId"></div>
当 div 为空时,我想隐藏 h3 元素。我愿意更改 html 结构,但 h3 必须在 div 之外,因为它的内容是动态更改的。
有没有办法在 CSS 中做到这一点?
等等,你会在这里得到一些很好的答案。但我的解决方案是创建一个 css 类,然后将其分配给 h3 和 div 标签,然后使用 jquery 选择器使用 css 类获取它们。现在,如果索引 1 的 innertext 处的元素 = null 或为空,那么您将获得一系列标签,那么索引 0 处的元素应该隐藏。我希望这个能帮上忙
使用::before css 选择器添加标签。
使用:empty选择器隐藏空/空值的标签
(两者都需要 IE9+)
HTML
<div class="label l_colour"></div>
<div class="label l_size"></div>
<div class="label l_shape"></div>
CSS
/* HIDE IF EMPTY*/
.label:empty { display: none; }
/* LABEL STYLES */
.label::before { font-weight:bold; }
/* LABEL VALUES */
.l_colour::before { content:"Colour: "; }
.l_size::before { content: "Size: "; }
.l_shape::before { content: "Shape: "; }
这个问题只能在客户端使用 JavaScript(或其库之一)来解决。使用纯 JavaScript,我建议:
function hideIfNextEmpty(el) {
var text = 'textContent' in document ? 'textContent' : 'innerText';
if (el.nextElementSibling[text].replace(/\s/g,'').length === 0) {
el.style.display = 'none';
}
}
hideIfNextEmpty(document.querySelector('h3.hideIfDivEmpty'));
纯 CSS 版本不会有很好的浏览器支持。它将涉及将标题标签放在内容之后,然后操作元素的位置。
这是一个非常复杂的纯 CSS 解决方案。IE 9+。您应该按照其他人的建议使用 JavaScript 来执行此操作。
article p:empty + header {
display: none;
}
article p:empty {
margin: 0;
}
article p {
float:left;
}
article header {
position: absolute;
top: 0;
}
article header h1 {
margin: 0;
}
article > p:first-of-type:not(:empty) {
padding-top: 1em;
}
article {
position: relative;
}
/* include clearfix */
<article class="clearfix">
<p></p>
<header><h1>Hidden article</h1></header>
</article>
<article class="clearfix">
<p>Cras mattis consectetur purus sit amet fermentum. Maecenas faucibus mollis interdum. Cras mattis consectetur purus sit amet fermentum. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Cras mattis consectetur purus sit amet fermentum. Nulla vitae elit libero, a pharetra augue.</p>
<header><h1>Porta Malesuada</h1></header>
</article>
输入的内容如何<div>
?因为非 JS 解决方案只涉及输入类(例如“隐藏”)。如果您在 HTML 中手动输入内容,那么您可以自己添加类。如果您通过模板动态加载内容,那么您应该能够编写一些简单的逻辑,<h3>
根据要输入到<div>
.
我愿意改变html结构......
答案是肯定的,这种结构灵活性。让 DIV 在 H3 元素之前并添加以下 CSS 规则:
// testing purposes only | see css and new html structure
document.querySelector('button').addEventListener('click', function() {
var el = document.querySelector('#divId');
if(el.textContent.length > 0) {
el.textContent = "";
} else {
el.textContent = "Hello world!";
}
});
div#divId:empty + h3.hideIfDivEmpty {
display: none;
}
<div id="divId">Hello world!</div>
<h3 class="hideIfDivEmpty">title</h3>
<!-- Button adds and removes text within div -->
<button>Toggle Text</button>