Get element width in px

后端 未结 6 1536
-上瘾入骨i
-上瘾入骨i 2020-12-10 13:06

How to get element width in pixels (px)? jQuery always returns value in percent (pct).

HTML



        
相关标签:
6条回答
  • 2020-12-10 13:19

    How many items have the class myElement? Consider using an id, not a class, as getting the width of two elements is not really possible (or logically understandable IMO).

    I made a little demo, and for me, it outputs the width in pixels for a single span element with a width of 100% (for me, it alerts something around 400): http://jsfiddle.net/LqpNK/3/.

    By the way, <span> element's can't have a set width or height, so setting their width and height does you no good. Instead, display them as a block element (so just replace <span> with <div>, or add display: block; to the CSS of .myElement).

    0 讨论(0)
  • 2020-12-10 13:33

    I have experienced like in this post: jQuery width() not returning correct value on a div with generated content. If the div is not displayed earlier or are loading content dynamically, the .width() function returns the percentage value, but till the element is fully loaded the same .width() function will return width in pixels.

    0 讨论(0)
  • 2020-12-10 13:34

    From the jQuery documentation on width()

    The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

    So it returns pixels if the pixel width is defined, but you are defining the width in %

    0 讨论(0)
  • 2020-12-10 13:35

    This worked for me:

    document.getElementById().offsetWidth;
    
    0 讨论(0)
  • 2020-12-10 13:36

    Maybe

    elt.getBoundingClientRect().width
    
    0 讨论(0)
  • 2020-12-10 13:38

    .css('width') should return 100%, however .width() should (as described here http://api.jquery.com/width/) return a unit-less pixel amount. I created a jsfiddle to demonstrate: http://jsfiddle.net/yxCav/

    0 讨论(0)
提交回复
热议问题