2014-12-02 85 views

回答

1

$('.item-image').css('background-image', 'url('+$('.item-image img').attr('src')+')');

2

試試這個:

var imageSrc = $(".item-image img").attr("src"); 
$(".item-image").css("background-image", "url('" + imageSrc + "')"); 
1

這將讓每.item圖像DIV並應用相應的後臺刪除原始圖像

$('.item-image').each(function() { 
    var that = $(this); 
    var url = that.find('img').attr('src'); 
    that.empty().css({'background':'url("' + url + '") no-repeat 50% 50%'});  
}); 
+0

爲什麼50%50%?其餘的似乎沒問題。 – 2014-12-02 12:19:44

+1

這將圖像集中在div內,隨意刪除它們或根據需要更改它們 – kapantzak 2014-12-02 12:21:13

0

如果你想爲'我設置背景圖像TEM圖像」元素 試試這個:

var src = $('.item-image img').attr('src'); 
$()$('.item-image').css('background-image', 'url('+ src +');'); 
0
  1. 圖片src爲母公司的div backgound

    $('.item-image').css('background-image', 'url('+$('.item-image img').attr('src')+')');

  2. 但仍然背景不會顯示出來,因爲DIV需要heightwidth等等您還需要獲取圖像w/h

    $('.item-image').css({'height' : $('.item-image img').outerHeight(), 'width' : $('.item-image img').outerWidth()});

  3. 現在<img/>標籤不是有用的,如果你已經使用背景相同的圖像,所以圖像刪除

    $('.item-image img').remove();

組合代碼

$('.item-image').css({ 
    'background-image': 'url('+$('.item-image img').attr('src')+')', 
    'height' : $('.item-image img').outerHeight(), 
    'width' : $('.item-image img').outerWidth()}); 
$('.item-image img').remove(); 
0

我已經更新你的jsfiddle的例子。我已經假設你想用原始圖像的值設置div的寬度和高度。如果沒有,你應該能夠根據自己的需要進行更新。記住你需要設置寬度和高度,否則你根本看不到任何東西!

我在JavaScript中使用了一些註釋來解釋。

HTML:

<div class="item-image" style="margin-left: -154px; margin-right: -154px;"> 
    <img src="http://mylonhom.t8.ext.starberry.com/images/header_images/placeholder_image.jpg" alt="" itemprop="image" /> 
</div> 

的JavaScript:

// We wan't to grab all div's with the item-image class. 
// Since it is a class, we must prepare to have more than one div 
// with the item-image class 
$('.item-image').each(function (itemIndex, item) { 
    var $item, $image, imageSrc, imageWidth, imageHeight; 

    // Set a reference to the div and fetch the first available image 
    $item = $(item); 
    $image = $item.find('img').eq(0); 

    // Did we fetch an image? 
    if ($image) { 
     // Let's fetch its source attribute 
     imageSrc = $image.attr('src'); 
     imageWidth = $image.outerWidth(); 
     imageHeight = $image.outerHeight(); 

     // Now set it as a background to the div 
     $item.css({ 
      'background-image': 'url(\''+imageSrc+'\')', 
      'background-repeat': 'no-repeat', 
      'width' : imageWidth + 'px', 
      'height': imageHeight + 'px' 
     }); 

     // Finally, remove the img tag from the div, we don't 
     // need it there anymore 
     $image.remove(); 
    } 
}); 

http://jsfiddle.net/96h4wmkf/4/