Get width in pixels from element with style set with %?

后端 未结 7 1696
庸人自扰
庸人自扰 2021-01-31 00:57

I have this element:

I want to get it\'s width in pixels. I just tried this:

7条回答
  •  灰色年华
    2021-01-31 01:39

    Not a single answer does what was asked in vanilla JS, and I want a vanilla answer so I made it myself.

    clientWidth includes padding and offsetWidth includes everything else (jsfiddle link). What you want is to get the computed style (jsfiddle link).

    function getInnerWidth(elem) {
        return parseFloat(window.getComputedStyle(elem).width);
    }
    

    EDIT: getComputedStyle is non-standard, and can return values in units other than pixels. Some browsers also return a value which takes the scrollbar into account if the element has one (which in turn gives a different value than the width set in CSS). If the element has a scrollbar, you would have to manually calculate the width by removing the margins and paddings from the offsetWidth.

    function getInnerWidth(elem) {
        var style = window.getComputedStyle(elem);
        return elem.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - parseFloat(style.borderLeft) - parseFloat(style.borderRight) - parseFloat(style.marginLeft) - parseFloat(style.marginRight);
    }
    

    With all that said, this is probably not an answer I would recommend following with my current experience, and I would resort to using methods that don't rely on JavaScript as much.

提交回复
热议问题