【发布时间】:2012-06-08 20:22:20
【问题描述】:
奇怪的问题。我有一组图像,其中包含一些我想在 div 中使用的属性(作为标题)。使用每个,我想获取图像的宽度(和一些其他属性),以正确对齐动态生成的 div(作为图像的标题)。
img = $('img')
img.each(function(index){
var width = $(this).width();
console.log(width);
// other properties
$('<div class="caption">Some text</div>').insertAfter($(this));
$(this).next().css({
'width': width
// other properties
});
但是,有时 $(this).width() 会得到正确的值,有时会得到 0。当在方向栏中按下返回时表现特别好,但当我按下 Ctrl+R 但仅在 Chrome 中时则不然。它在所有浏览器中的工作方式都不一样,所以很乱。我认为 Jquery 试图在加载图像之前检索 width(),所以我将代码包装在 document.ready(function(){}) 而不是 (function(){})() 但它不起作用无论哪种方式。
会发生什么?作为参考,这些是应用于图像的样式:
display: block;
padding: 4px;
line-height: 1;
max-width: 100%;
margin-left: auto;
margin-right: auto;
所以我想获得计算出的宽度(据我所知,它应该由 .css() 检索,但在这种情况下,不一致)。
问候
【问题讨论】:
-
查看这个问题的答案:stackoverflow.com/questions/7983278/…
-
不确定你的意思。宽度()与 CSS('宽度')?
-
.outerWidth() 得到计算出来的尺寸。
-
不,这根本行不通。
标签: javascript jquery html css image