2014-12-02 119 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/