在jQuery中将图像SRC转换为背景图像

时间:2010-10-27 13:37:03

标签: jquery

How to set the image src using jQuery

我希望与此jQuery代码片段相反。我需要一些代码来转

<img src="images/filename.jpg">

成为

<div class="imageBox" style="background:url(images/filename.jpg)"></div>

我上下搜索试图寻找可以做到这一点的东西,但却空洞了。我不是jQuery大师,所以我很感激有人可以提供任何帮助。感谢

1 个答案:

答案 0 :(得分:7)

$("img").each(function(i, elem) {
  var img = $(elem);
  var div = $("<div />").css({
    background: "url(" + img.attr("src") + ") no-repeat",
    width: img.width() + "px",
    height: img.height() + "px"
  });
  img.replaceWith(div);
});

Live Demo