2

jQuery method .width() was used to get the width of the generated element as:

html: 
<div class='row-fluid' id='photo-preview'></div>
javascript:
 for(i = 0;i < 4;i++){
    var imageSpan = "<div class='span3' id='span_" + i + "'><img src='" + images[i] +"'></div>"
    $('#photo-preview').append(imageSpan);
    var w = $('#span_' + i).width(); 
    console.log(w);
  }

But it got the incorrect value of width. It was the value of percentage instead of pixel. E.g, w should be 400 (400px) but the js got 80 (80%).

I thought the problem may be because the element was dynamically generated. In the console I can got the right value with .width() when all the elements were loaded.

Any ideas to work around with it?

4

2 回答 2

4

您必须等待图像的加载事件才能获得正确的高度。

var img = '<img src="img_path.jpg">';
$(img)
    .load(function() {
        console.log("width", $(this).width());
    })
    .appendTo('#photo-preview');

编辑:与您的示例相匹配:

html: 
<div class='row-fluid' id='photo-preview'></div>
javascript:
 for(i = 0;i < 4;i++){
    var img = "<img src='" + images[i] +"'>";
    $(img)
        .load(function() {
            console.log("width", $(this).width());
        })
        .appendTo("<div class='row-fluid' id='photo-preview'>")
        .appendTo('#photo-preview');

  }
于 2013-01-12T23:14:30.813 回答
-1

尝试使用offsetWidth

IE

var w =  $('#span_' + i).offsetWidth;
console.log(w);

这是我做的一个非常愚蠢的小提琴。我将宽度设置为 80%。如果你去控制台,你应该看到像素宽度(448 px)

http://jsfiddle.net/bwm5s/

于 2013-01-12T23:06:38.830 回答