改变元素的尺寸

4
我希望用 jQuery 将许多元素 (figcaption) 的尺寸改变为 img 尺寸,请帮助我。
var width = $("div[caption='true'] img").attr("width");

var height = $("div[caption='true'] img").attr("height");

$("div[caption='true'] figcaption").css("width",width);
$("div[caption='true'] figcaption").css("height",height);

jsfiddle link

3个回答

1

试试这个:

$(function() {
    $("div[caption='true']").each(function() {
        var $this  = $(this);
        var image  = $this.find('img')
        var width  = image.width();
        var height = image.height();

        $this.find('figcaption').width(width).height(height);
    });
});

jsFiddle:http://jsfiddle.net/8ge1wvpt/11/

JavaScript 代码片段:http://jsfiddle.net/8ge1wvpt/11/

0

您当前的代码将每个figcaption的高度和宽度设置为第一个图像的高度和宽度。请尝试以下代码:

$(document).ready( function() {

    $("div[caption='true']").each(function() {
        var $this = $(this);
        var width = $("img", $this).attr("width");
        var height = $("img", $this).attr("height");
        $("figcaption", $this).css({"height":height, "width":width});
    });

});

演示

下面是代码片段:

$(document).ready( function() {
 
 
    $("div[caption='true']").each(function() {
        var $this = $(this);
        var width = $("img", $this).attr("width");
        var height = $("img", $this).attr("height");
        $("figcaption", $this).css({"height":height, "width":width});
    });
 
});
*{margin:0;padding:0;}
.imgs{position:relative;}
figcaption{position:absolute;top:0;
    background-color:rgba(0,0,0,0.4);}
figcaption h3{text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="imgs" caption="true">
  
   <img src="http://goo.gl/uRvjRS" width="200" height="250" alt=""/>
   <figcaption>
    <h3>IMGs Caption 1</h3>
   </figcaption>
  
  </div>
  
  <div class="imgs" caption="true">
  
   <img src="http://goo.gl/uRvjRS" width="100" height="100" alt=""/>
   <figcaption>
    <h3>IMGs Caption 2</h3>
   </figcaption>
  
  </div>
  
  <div class="imgs" caption="true">
  
   <img src="http://goo.gl/uRvjRS" width="300" height="200" alt=""/>
   <figcaption>
    <h3>IMGs Caption 3</h3>
   </figcaption>
  
  </div>


谢谢,但您能解释一下$this具体是做什么的吗? - Amir Sasani
你正在缓存 $(this) 对象。这是一种代码优化的方法,但不完全必要。在这里阅读更多信息:https://dev59.com/60rSa4cB1Zd3GeqPYrVR - Turnip

0

您可以通过使用函数填写css值来完成它:

$(document).ready( function() {
  $("img + figcaption")
    .css("width",function() { return $(this).prev().attr("width");})
    .css("height",function() { return $(this).prev().attr("height"); });
});

这将匹配任何<img>后跟<figcaption> - 除非您将其用于其他用途,否则不需要caption="true"属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接