使用jQuery从img属性更改wp-caption内联样式 [英] Use jQuery to change wp-caption inline style from img attribute

查看:94
本文介绍了使用jQuery从img属性更改wp-caption内联样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery修改WordPress [caption]短代码的HTML,其HTML基本上是这样的:

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>

此问题(至少对我而言)是,当存在图像标题时,WordPress会向.wp-caption容器添加额外的10px.我想将此内联样式重置为与图像的width属性相同.我不确定该var部分的工作方式(或者是否有更好的串联字符串的方法),并且我希望在正确的方向上提供帮助:

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:

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

更新1:现在,我只需要弄清楚页面上有多张图像时的工作方式. 我尝试将其包装在.each(function(n)中,但它仍采用第一个图像的宽度并将其应用于所有容器.

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

更新2:已解决-请参见此线程

推荐答案

尝试一下:

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

这篇关于使用jQuery从img属性更改wp-caption内联样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆