奇怪的问题。我有一组图像,其中包含一些我想在 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() 检索,但在这种情况下,不是始终如一的)。
问候
最佳答案
jQuery 不会等待 $(document).ready()
中的图像。
如示例 5 here 中所述,请尝试使用 $(window).load()
关于javascript - 加载时不可靠地检索图像中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10886771/