Javascript 没有jquery的outerWidth
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5195402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
outerWidth without jquery
提问by Martin Borthiry
It's possible to get the element outerWidth using the dom?
可以使用dom获取元素outerWidth吗?
Ej:
Ej:
var width = document.getElementById('myDiv').outerWidth;
回答by Sean
No, but you can get offsetWidth, which is probably what you want.
不,但您可以获得 offsetWidth,这可能是您想要的。
From http://www.quirksmode.org/dom/w3c_cssom.html
来自http://www.quirksmode.org/dom/w3c_cssom.html
offsetWidthand offsetHeight
offsetWidth和offsetHeight
The width & height of the entire element, including bordersand padding(excluding margins).
整个元素的宽度和高度,包括边框和内 边距(不包括边距)。
clientWidthand clientHeight
clientWidth和clientHeight
The width & height of the element including padding(excluding bordersand margins)
元素的宽度和高度,包括填充(不包括 边框和边距)
See this fiddlefor an example.
有关示例,请参阅此小提琴。
var elm = document.querySelector('div');
document.body.innerHTML += `
clientWidth: ${elm.clientWidth} px
<br>
scrollWidth: ${elm.scrollWidth} px
<br>
offsetWidth: ${elm.offsetWidth} px`
div{
width : 200px;
padding : 10px;
border : 10px solid gold;
margin : 10px;
background : lightgreen;
}
<div></div>
If you use jQuery you have more options: width, innerWidth and outerWidth properties. http://api.jquery.com/category/manipulation/style-properties/
如果你使用 jQuery,你有更多的选择:width、innerWidth 和 outerWidth 属性。 http://api.jquery.com/category/manipulation/style-properties/
回答by Dylan Maxey
Sean provided the perfect solution for outerWidth().
Sean 为outerWidth() 提供了完美的解决方案。
Just to add to that, if you're looking for a substitution for any or all of the jQuery dimension getters, see my solution below.
补充一点,如果您正在寻找任何或所有 jQuery 维度 getter 的替代品,请参阅下面的解决方案。
Note:this also provides the correct dimensions even with * { box-sizing: border-box }
注意:这也提供了正确的尺寸,即使* { box-sizing: border-box }
getWidth(el, type) {
if (type === 'inner') // .innerWidth()
return el.clientWidth;
else if (type === 'outer') // .outerWidth()
return el.offsetWidth;
let s = window.getComputedStyle(el, null);
if (type === 'width') // .width()
return el.clientWidth - parseInt(s.getPropertyValue('padding-left')) - parseInt(s.getPropertyValue('padding-right'));
else if (type === 'full') // .outerWidth(includeMargins = true)
return el.offsetWidth + parseInt(s.getPropertyValue('margin-left')) + parseInt(s.getPropertyValue('margin-right'));
return null;
}