开发者

jQuery: get style attribute and append it to new <div>

Currently I have an image like this (created by CKEditor):

<img src="foo.jpg" style="float: left; margin-left: 20px;" alt="Image开发者_StackOverflow社区 text">

I want to add a div around this image and extract the text from the alt-tag into a span.

$(document).ready(function () {
    $("#foo img").each(function() {
        $(this).wrap("<div class='imgtxt' />");
        $(this).after($("<span />").text($(this).attr("alt")));
     });
});

So far so god! But I also want to get the style attributes from the img and add that to the CSS of the newly created div. How can I achieve this?


Try this

$(document).ready(function () {
    $("#foo img").each(function() {
        $(this).wrap("<div class='imgtxt' />");
        $('.imgtxt').attr('style', $(this).attr('style'));
        $(this).after($("<span />").text($(this).attr("alt")));
     });
});


You can use this:

$(document).ready(function () {
    $("#foo img").each(function(index) {
        $(this).wrap("<div id='newdiv" + index + "'" class='imgtxt' />");
        $(this).after($("<span />").text($(this).attr("alt")));
        $("#newdiv" + index).attr('style', $(this).attr('style');
     });
});

You're basically creating a unique ID for each DIV and then applying the style each time


$(this).closest('div.imgtxt').attr('style', $(this).attr('style'));

closest() will grap your div you just created. I'd also recommend changing the code to something like this:

$("#foo img").each(function() {
    var $this = $(this);
    $this.wrap("<div class='imgtxt' />");
    $this.after($("<span />").text($this.attr("alt")));
    // etc.
 });

This way you are not looking up/making a jQuery object every time $(this) is called!


Replace this line $(this).wrap("<div class='imgtxt' />"); with:

$(this).wrap("<div class='imgtxt' style=\"" + $(this).attr("style") + "\" />");

This takes the style attribute of the image and adds it to the new div.


$('img').each(function() {
    var alt   = $(this).attr('alt'),
        style = $(this).attr('style');
    $(this).after("<span>" + alt + "</span>")
           .next('span')
           .andSelf()
           .wrapAll('<div class="imgtxt" style="'+style+'"></div>');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜