jQuery用div替换图像并将图像设置为背景

时间:2012-11-18 07:05:46

标签: jquery html css

我有一些图像..例如:

<div class="image-container">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p1.jpg" class="image-style" typeof="foaf:Image">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p2.jpg" class="image-style" typeof="foaf:Image">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p3.jpg" class="image-style" typeof="foaf:Image">
    <img width="174" height="174" src="http://mysite.com/images/portfolio/p4.jpg" class="image-style" typeof="foaf:Image">
</div>

我希望使用jQuery遍历每个图像并使其成为div然后将图像作为背景图像进行设置......就像这样:

<div class="image-container">
        <div style="background-image:url(http://mysite.com/images/portfolio/p1.jpg)"><span>image</span></div>
        <div style="background-image:url(http://mysite.com/images/portfolio/p2.jpg)"><span>image</span></div>
        <div style="background-image:url(http://mysite.com/images/portfolio/p3.jpg)"><span>image</span></div>
        <div style="background-image:url(http://mysite.com/images/portfolio/p4.jpg)"><span>image</span></div>
</div>

我知道如何为一个人做这个,但不确定通过我的父div(image-container)中的所有图像并转换它们的最佳方法。

非常感谢任何帮助。 ç

3 个答案:

答案 0 :(得分:3)

您可以使用replaceWith方法:

$('.image-container img').replaceWith(function(i, v){
    return $('<div/>', {
        style: 'background-image: url('+this.src+')',
        html: '<span>image</span>'
    })
})

http://jsfiddle.net/FD9gV/

答案 1 :(得分:1)

哦,你可以随时做好每一件事

$('div.image-container img').each( function(i,o){
    // function for one of your img tags
    // which is accessible easily via $(o), e.g.
    $(o).replaceWith('<div style="background:url(' + $(o).attr('src')+')"><span>image</span></div>');

});

答案 2 :(得分:1)

请试试这个; :) http://jsfiddle.net/x5HhV/

jquery change background-image

希望这符合原因:)

API:http://api.jquery.com/replaceWith/

<强>码

$("div.image-container > img").each(function(index) {
    index = index + 1
    $(this).replaceWith('<div style="background-image:url(http://mysite.com/images/portfolio/p' + index + '.jpg)"><span>image</span></div>');

    alert(index + ' HTML is now changed to => ' + $("div.image-container").html());

});

​