0

我有一个带有 css 集的图像元素

height: 64px;
width: auto;

当我尝试使用.outerHeight()&通过 jQuery 获取高度和宽度时.outerWidth(),我可以正确获取高度,但宽度返回为 0。我什至尝试过 width(),innerWidth() 仍然相同。

我必须动态设置图像。也许这有一些问题。这是小提琴http://jsfiddle.net/abdulpathan/0vrbnpe3/3

有人可以帮我解决这个问题。

谢谢

4

1 回答 1

2

解决方案是在图像加载后简单地获取宽度。

jQuery(document).ready(function() {
  $('#test').on("load", function() {
  
  var height = $('#test').outerHeight();
  var width = $('#test').outerWidth();
  width = width.toFixed(2); // rounds it
  console.log('Width:' + width);
  console.log('Height:' + height);
  })
  $('#test').attr('src', 'https://www.gstatic.com/webp/gallery3/2.png'); 
});
.test-img {
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <img id="test" class="test-img">
</div>

于 2019-07-06T16:53:11.760 回答