我有一個包含多個段落的div(博客文章)。只包含圖像的目標段落
其中一些包含文本,其他文本+圖像和其他唯一圖像。
我想只針對僅包含圖像的段落,並設置text-align:center
這可能僅僅使用CSS或者是JS要求?
有什麼建議嗎?
感謝
我有一個包含多個段落的div(博客文章)。只包含圖像的目標段落
其中一些包含文本,其他文本+圖像和其他唯一圖像。
我想只針對僅包含圖像的段落,並設置text-align:center
這可能僅僅使用CSS或者是JS要求?
有什麼建議嗎?
感謝
下增加了一個特殊的CSS類僅包含的img標籤和空白的所有p標籤:
$('.blog-post p').each(function(i){ // For each paragraph
if (($(this).find('img').length) && // If there's an image
(!$.trim($(this).text()).length)) // and there's no text
{
$(this).addClass('imgOnly'); // Add a special CSS class
}
});
的trim()
函數用於text()
以確定文本只包含空格。
示例內容:
<div class="blog-post">
<p>Text</p>
<p><span>Text</span></p>
<p><img/></p> <!-- CSS class will be added -->
<p>Text <img/></p>
<p><span>Text</span><img/></p>
<p><img/> Text <img/></p>
<p><img/><img/></p> <!-- CSS class will be added -->
<p><img/> <img/></p> <!-- CSS class will be added -->
</div>
要做到這一點,你可以使用JavaScript和寫一個函數吧,你最好使用JavaScript庫的jQuery。當你有它的功能,你可以在以後添加新的段落和圖像,而無需編寫更多的代碼。
我會寫一個例子,但我沒有太多時間。我希望我能幫到你一點點
Css是不夠的。您可以使用基於父母的Css規則,但不基於兒童。例如,您可以定位段落中出現的所有圖像。這些屬性將應用於圖像,而不適用於該段落。例如:
p img
{
/* properties */
}
選項保持JavaScript或服務器端,例如,你可以一個特定的類名稱分配給基於內容(.imageOnly或.mixedContent)段落。
這個例子可以幫助你:demo on jsFiddle
jQuery代碼:
$(function() {
var divs = $('.blog-post > div');
$.each(divs, function(i, div) {
/* cache variable */
var $div = $(div);
if (!($div.find('p')[0])) { /* if there are no one p tag inside div */
$div.addClass('only-images');
}
});
});
CSS:
.blog-post > .only-images {
background-color: red; /* color is demo only */
}
所以我的例子中添加類只到第三DIV僅包含此前的圖像充足的HTML標記:
<div class="blog-post">
<div>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
</div>
<div>
<p>some text</p>
<img src="//placekitten.com/g/100/100" alt="" />
</div>
<div> <!-- only this div would be applied class `only-images` customizable by css -->
<img src="//placekitten.com/g/100/100" alt="" />
<img src="//placekitten.com/g/100/100" alt="" />
</div>
</div>
您將需要JS。 – BoltClock
你接受jQuery嗎? –
jquery聽起來不錯,考慮到沒有css posible – thedev