[英]Display only one paragraphs…no matter if there are more, with blank, with white-space, with class…only and only with css
我正在尋找css屬性來隱藏帶有或不帶有css類的段落,如果它包含空格()或空白,但是我希望至少保留一個段落,無論是否包含更多段落。
如果段落為空或包含空白(),則最好隱藏段落,最好僅使用CSS ...如果根本沒有其他選項,則僅使用JavaScript / jquery
// Ideally I don't want to use javascript/jquery $("p").html(function(i, html) { return html.replace(/ /g, ''); });
p:nth-child(n+2):empty, p:nth-child(n+2):blank, .MsoNormal p:nth-child(n+2):empty, .MsoNormal p:nth-child(n+2):blank { margin: 0 0 0px; display: none; } p::before { content: ' '; } p:empty::before { content: ''; display: none; } p:first-child:empty+p:not(:empty)::before { content: ''; } p:first-child:empty+p:empty+p:not(:empty)::before { content: ''; } p::after { content: ''; display: none; p:empty::after { display: none; } p:first-child:empty+p:not(:empty)::after { content: ''; } p:first-child:empty+p:empty+p:not(:empty)::after { content: ''; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> some text - 1 </div> <p> </p> <p> </p> <p> </p> <div> some text - 2 </div> <p> </p> <div> some text - 3 </div> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <div> some text - 4 </div> <p> </p> <p> </p> <div> some text - 5 </div> <p></p> <p></p> <div> some text - 6 </div> <p class="MsoNormal"></p> <p></p>
<b>So above html, I would like to display:</b>
<div> some text - 1 </div>
<p> </p>
<div> some text - 2 </div>
<p> </p>
<div> some text - 3 </div>
<p> </p>
<div> some text - 4 </div>
<p> </p>
<div> some text - 5 </div>
因此,我試圖通過偽類和偽元素來獲得它,但是沒有運氣。 (注意-我有在這里工作的jQuery,但不想使用它。)
據我所知,您不能僅使用CSS進行此操作。
使用jQuery是最簡單,最干凈的方法。 我不明白為什么要使用jQuery,但您不想使用它,但是使用純js進行此操作對我來說更“難看”。 雖然我給你2條代碼。
JS代碼:
// get the elements and transform from HTMLCollection object to array
var array_p = document.getElementsByTagName("P");
array_p = Array.prototype.slice.call(array_p);
array_p.forEach(function(value, index) {
var text = value.innerHTML;
text = text.replace(new RegExp(' ', 'g'), '');
text = text.replace(new RegExp(' ', 'g'), '');
value.style.display = "none";
});
例如,如果您想使用它,則添加一個jQuery代碼:
$.each($("p"), function(index, value) {
var text = $(this).html();
text = text.replace(new RegExp(' ', 'g'), '');
text = text.replace(new RegExp(' ', 'g'), '');
if (text.length == 0) {
$(this).css("display", "none");
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.