我已經更新你的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