3

jQuery を使用して、特定のクラスを持つすべての img 要素を背景を持つ div に切り替えたいと思います。だからすべて:

<img class="specific" src="/inc/img/someimage.png" />

なる:

<div class="specificDiv" style="background: url(/inc/img/someimage.png); width: fromImageElementPX; height: fromImageElementPX;"></div>

css3を使用して角を丸めることができるように、これを行いたいと思います。CMS ユーザーである顧客は、IMG 要素を挿入することしかできません。

前もって感謝します。

4

5 に答える 5

4

私が考えることができる最も簡単な方法:

$('.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>';
});
于 2010-12-09T18:15:37.073 に答える
2
$('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
})
于 2010-12-09T18:12:11.257 に答える
1

これはうまくいくはずですが、私はそれをテストしていません。

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);
于 2010-12-09T18:06:31.053 に答える
0

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);
  });
});

于 2010-12-09T18:08:34.147 に答える
0

別のオプション (Andrew Koester からコードを取得) は、それをプラグインに入れることです。これがどのように見えるかです...

$.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);  
  });
};

次に、それを実行するには、次のように呼び出すだけです...

$(".specific").replaceImage();
于 2010-12-09T18:16:47.800 に答える