开发者

Turn image SRC into background-image in jQuery

开发者 https://www.devze.com 2023-01-22 00:48 出处:网络
How to set the image src using jQuery I am looking to do the opposite of what this jQuery snippet does.I need a bit of code that will turn

How to set the image src using jQuery

I am looking to do the opposite of what this jQuery snippet does. I need a bit of code that will turn

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

to become

<div class="imageBox" style="background:url(images/filename.jpg开发者_C百科)"></div>

I've searched up and down trying to find something that will do this but have come up empty. I'm no jQuery guru, so I would appreciate any help someone could offer. Thanks


$("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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号