Change img to div with background, with jQuery
I'd like to use jQuery to switch all img elements with a specific class to a div with background. So that all:
<开发者_开发问答;img class="specific" src="/inc/img/someimage.png" />
Becomes:
<div class="specificDiv" style="background: url(/inc/img/someimage.png); width: fromImageElementPX; height: fromImageElementPX;"></div>
I'd like to do this so that I can round the corners using css3. The CMS user, customer, will only be able to insert IMG elements.
Thanks in advance.
The easiest way I can think of:
$('.specific').replaceWith(function () {
var me = $(this);
return '<div class="specificDiv" style="background: url(' + me.attr('src') + '); width: ' + me.width() + 'px; height: ' + me.height() + 'px;"></div>';
});
$('img.specific').each(function(){ //iterate through images with "specific" class
var $this = $(this), //save current to var
width = $this.width(), //get the width and height
height = $this.height(),
img = $this.attr('src'), //get image source
$div = $('<div class="specificDiv"></div>')
.css({
background: 'url('+img+')', //set some properties
height: height+'px',
width: width+'px'
});
$this.replaceWith($div); //out with the old, in with the new
})
This should work, but I haven't tested it.
var origImage = $(".specific");
var newDiv = $("<div>").addClass("specificDiv");
newDiv.css("background-image", "url('" + origImage.attr("src") + "')");
newDiv.width(origImage.width()).height(origImage.height());
origImage.replaceWith(newDiv);
Another option (taking the code from Andrew Koester), is to put it in a plugin. Here's what it might look like...
$.fn.replaceImage = function() {
return this.each(function() {
var origImage = $(this);
var newDiv = $("<div>").attr("class", "specificDiv");
newDiv.css("background", "url('" + origImage.attr("src") + "')");
newDiv.width(origImage.width()).height(origImage.height());
origImage.replaceWith(newDiv);
});
};
Then, to execute it, just call something like this...
$(".specific").replaceImage();
http://jsbin.com/ozoji3/3/edit
$(function() {
$("img.rounded").each(function() {
var $img = $(this),
src = $img.attr('src'),
w = $img.width(),
h = $img.height(),
$wrap = $('<span class="rounded">').css({
'background-image': 'url('+ src +')',
'height': h+'px',
'width': w+'px'
});
$(this).wrap($wrap);
});
});
精彩评论