Resize an item

I want to resize elements (figcaption) to img sizes using jquery plz help me

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

+4
source share
3 answers

Your current code sets each width and width figcaptionaccording to the first image. Try the following:

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

});

Demo

Below is a snippet:

$(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>
Run codeHide result
0
source

Try the following:

$(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/

+1
source

, 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", - .

0

Source: https://habr.com/ru/post/1568128/


All Articles