我已经更新你的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/
为什么50%50%?其余的似乎没问题。 – 2014-12-02 12:19:44
这将图像集中在div内,随意删除它们或根据需要更改它们 – kapantzak 2014-12-02 12:21:13