3

我有一个图像 div .. 例如:

<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) 中的所有图像并转换它们的最佳方法。

任何帮助将不胜感激。C

4

3 回答 3

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/

于 2012-11-18T07:24:23.433 回答
1

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

jQuery更改背景图像

希望这符合原因:)

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());

});

​
于 2012-11-18T07:23:48.220 回答
1

Oh well to do through each you can always do 哦,做好每一件事

$('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>');

});
于 2012-11-18T07:13:27.833 回答