目标段落仅包含图像

时间:2012-06-14 11:41:34

标签: javascript html css

我有一个包含多个段落的div(博客文章)。

其中一些包含文字,其他文字+图像和其他图像。

我想仅定位仅包含图片的段落并设置text-align:center

这只能使用css还是需要js?

有什么建议吗?

由于

5 个答案:

答案 0 :(得分:2)

以下为所有仅包含img标签和空格的p标签添加了一个特殊的CSS类:

$('.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>

答案 1 :(得分:1)

此示例可以帮助您: 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 */
}

因此,我的示例仅将类添加到仅包含此示例 HTML 标记中的图像的第三个div:

<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>​

答案 2 :(得分:0)

要做到这一点,你可以使用javascript并为它编写一个函数,你最好使用javascript库Jquery。当你有一个功能时,你可以稍后添加新的段落和图像,而无需编写更多的代码。

我会写一个例子,但我没有太多时间。我希望我能帮助你一点

答案 3 :(得分:0)

Css还不够。您可以使用基于父母的Css规则,但不能基于子女。例如,您可以定位段落中出现的所有图像。属性将应用于图像,而不是段落。例如:

p img
{
   /* properties */
}

选项仍然是Javascript或服务器端,例如,您可以根据内容(.imageOnly或.mixedContent)为段落指定特定的类名。

答案 4 :(得分:0)

我必须在没有jQuery的情况下执行此操作,然后我想到了以下内容:

document.querySelectorAll('p').forEach(function(p) {

    // if there's no image, stop
    if (p.querySelector('img') === null) {
        return;
    }

    // if there's text, stop
    if (p.innerText.trim() !== "") {
        return;
    }

    // otherwise, mark the paragraph
    p.classList.add('img-only');
});

仅在现代浏览器上进行了测试。

相关问题