简体   繁体   English

Javascript获取img的宽度和高度,并将其放入另一个类的css中

[英]Javascript get width and height of img and place it into css of another class

I can't seem to putting the width and height of an img into another class css. 我似乎无法将img的宽度和高度放入另一个类css中。 If you could just give me a hint that would be nice! 如果你能给我一个很好的提示! Here's my code: 这是我的代码:

$('.Main_hover').each(function() {
    var $this = $(this);
    var w = $this.find('img').width();
    var h = $this.find('img').height();
    $(".fusion-button-wrapper").css('height', h);
    $(".fusion-button-wrapper").css('width', w);
});

Of course its wrapped around a document.ready . 当然它包裹着一个文件。已经。

Here is the HTML where i want to take the width and height of the image: 这是我想要获取图像的宽度和高度的HTML:

<div class="imageframe-align-center">
  <span class="fusion-imageframe imageframe-none imageframe-1 hover-type-none Main_hover">
    <a class="fusion-no-lightbox" href="http://lowette.devel.growcreativity.be/portfolio-items/dummy3/" target="_self"> 
       <img src="http://lowette.devel.growcreativity.be/wp-content/uploads/2016/01/lowette_blok1_1.png" alt="Blok1_1" class="img-responsive">                </a>
 </span>
</div>

And here is the div class where i want to give the width and height: 这里是div类,我想给出宽度和高度:

<div class="fusion-button-wrapper"></div>

Its better to do what you are doing once img is loaded because webkit browsers set the height and width property after the image is loaded. 因为webkit浏览器在加载图像后设置了height和width属性,所以在加载img更好地做你正在做的事情。 Which may or may not be after document ready is completed. 完成文档准备后可能会或可能不会。

 $('.Main_hover img').load(function() { $(".fusion-button-wrapper").width(this.width); $(".fusion-button-wrapper").height(this.height); }); 
 .fusion-button-wrapper{ background: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="imageframe-align-center"> <span class="fusion-imageframe imageframe-none imageframe-1 hover-type-none Main_hover"> <a class="fusion-no-lightbox" href="http://lowette.devel.growcreativity.be/portfolio-items/dummy3/" target="_self"> <img src="http://lowette.devel.growcreativity.be/wp-content/uploads/2016/01/lowette_blok1_1.png" alt="Blok1_1" class="img-responsive"> </a> </span> </div> <div class="fusion-button-wrapper"></div> 

you can use height width function of jQuery and clientHeight clientWidth of javascript 你可以使用jQuery的height width函数和javascript的clientHeight clientWidth

$('.Main_hover').each(function() {
  var $this = $(this);
  var h = $this.find('img')[0].clientHeight;
  var w = $this.find('img')[0].clientWidth;
  $(".fusion-button-wrapper").height(h);
  $(".fusion-button-wrapper").width(w);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM