开发者

Use jQuery to change wp-caption inline style from img attribute

开发者 https://www.devze.com 2023-03-19 03:32 出处:网络
I\'m trying use jQuery to modify the HTML of the WordPress [caption] shortcode, whose HTML is basically like this:

I'm trying use jQuery to modify the HTML of the WordPress [caption] shortcode, whose HTML is basically like this:

<div class="wp-caption" style="width: 310px">
<img class="size-medium" src="..." width="300" height="200" alt="" />
<p class="wp-caption-text">The caption is here.</p>
</div>

The problem with this (for me at least) is that WordPress add an extra 10px to the .wp-caption container when an image caption in present. I want to reset this inline style to be the same as the width attribute of the image. I'm not exactly sure how the var parts of this should work (or if there's a better way to concatenate a string) and I'd appreciate any help in the right direction:

jQue开发者_运维百科ry().ready(function() {
    jQuery(".wp-caption").removeAttr("style");
    var width = jQuery(".wp-caption img").Attr(width);
    var width = jQuery(width).Prepend('width:');
    var width = jQuery(width).Append('px');
    jQuery(".wp-caption").attr('style', jQuery(width));
    });

Update 1: Now I just need to figure out how to work when there are multiple images on a page. I tried wrapping it in a .each(function(n) but it still takes the width from the first image and applies it to all the containers.

jQuery().ready(function() {
    jQuery(".wp-caption").each(function(n) {
    var width = jQuery(".wp-caption img").width();
    jQuery(".wp-caption").width(width);
    });
    });

Update 2: Resolved—see this thread.


Try this:

var width = jQuery(".wp-caption img").width();
jQuery(".wp-caption").width(width);


$(document).ready(function() {
    var width = $(".wp-caption img").attr("width") + "px";
    $(".wp-caption").css('width', width);
});
0

精彩评论

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