jQuery:为什么.width()有时在插入带有.html()的元素后返回0?

Jon*_*ing 20 jquery

我得到一些HTML并插入它.html(),之后我试图获得一个新插入的元素的宽度.width()(具有CSS规则).但有时 - 宽度未被拾取,并返回为0.

是因为JS在新创建的元素及其CSS中"超前"运行?我尝试过链接,.html('...').find('...').width()但有时候仍然无效.是什么原因,是否有解决方法?

编辑:按流行需求,示例:

/* ajax.response is:
    <div class="boxes">
        <div class="box width-A">test 1</div>
        <div class="box width-B">test 2</div>
        <div class="box width-C">test 3</div>
    </div> */

var boxOutput = $('.boxOutput'); /* .boxOutput is already on the page */
boxOutput.html(ajax.response);

// make width of ".boxes" equal to the sum of all ".box"

var boxWidth = 0;
$('.box', boxOutput).each(function(i) {
    boxWidth += $(this).width(); /* this is where sometimes width returns 0 */
});
$('.boxes', boxOutput).css('width', boxWidth);
Run Code Online (Sandbox Code Playgroud)

我的原始代码太长/太难以复制/粘贴,但这是我正在做的一个简单的事情(对不起,如果在某个地方有一个愚蠢的错误,我现在为时已晚:P).从ajax获取html后,将其放入div中,我想获得每个框的宽度(因为它可能不同),然后使用该宽度.同样,90%的时间,正确返回宽度.当有时宽度为0时,这是10%:(

Jos*_*osh 25

取决于什么浏览器.偶尔我会发现一些东西会破坏javascript运行时的同步渲染期望,我需要在下一个滴答中得到结果.

我试试:

$(elem).html(data);
setTimeout(function(){
    // Get the width here
},0);
Run Code Online (Sandbox Code Playgroud)

  • 对我来说0超时不起作用,但50个做了伎俩. (2认同)

小智 10

如果元素不可见,jQuery将返回零宽度.例如,我将一个项目插入隐藏的表单选项卡时遇到了同样的问题.暂时将它分配给可见的身体,我能够确定宽度:

$("body").append(el); // First assign it to the body so that it's visible
var width = el.width(); // The width will now be correct
wrapper.append(el); // Now place the element where you want it.
Run Code Online (Sandbox Code Playgroud)

需要注意的是,如果元素在分配给主体时继承了不同的样式,则宽度可能不正确.