【问题标题】:jQuery element outerWidth() returns 0jQuery 元素 outerWidth() 返回 0
【发布时间】:2019-11-15 22:33:43
【问题描述】:

我有一个带有 css 设置的图像元素

height: 64px;
width: auto;

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

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

谁能帮我解决这个问题。

谢谢

【问题讨论】:

  • 你提到的属性工作得很好:jsfiddle.net/qm4xp3rv。如果有一个完整的问题行为示例来显示您的 HTML、JS 和所有其他相关的 CSS,这将有所帮助
  • ^^ 例如,minimal reproducible example。发生这种情况的一些原因:浏览器尚未渲染元素,元素尚未在 DOM 中,元素被隐藏,...
  • 我必须动态设置图像。也许这有一些问题。这是小提琴jsfiddle.net/abdulpathan/0vrbnpe3/3

标签: jquery width outerwidth


【解决方案1】:

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

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>

【讨论】:

  • 谢谢,但我认为不需要所有这些计算,$('#test').outerWidth();load() 中完美运行。因为当图像完全加载后,您就拥有了正确所需的所有测量值。
  • @AbdulPathan 你是对的!我相应地更改了代码,现在它更简单了:)
猜你喜欢
  • 1970-01-01
  • 2014-04-06
  • 2017-03-03
  • 2015-10-12
  • 2012-03-03
  • 1970-01-01
  • 2018-03-29
  • 2021-12-10
  • 2012-04-19
相关资源
最近更新 更多