jQuery: Why does .width() sometimes return 0 after inserting elements with .html()?

前端 未结 6 1252
误落风尘
误落风尘 2021-02-07 00:57

I am getting some html and inserting it with .html(), after which I am trying to get the width of one of newly inserted elements with .width() (which h

6条回答
  •  猫巷女王i
    2021-02-07 01:26

    jQuery will return a zero width if the element is not visible. For example, I was having the same issue with an item being inserted onto a hidden form tab. Temporarily assigning it to the body, where it was visible, I was able to determine the width:

    $("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.
    

    One caveat is that if the element inherits different styling when assigned to the body then the width may not be correct.

提交回复
热议问题