Javascript 不带jquery的外径

Javascript 不带jquery的外径,javascript,Javascript,是否可以使用dom获取元素outerWidth Ej: 不,但你可以得到偏移网络宽度,这可能是你想要的 从 离网宽度和离网视野 整个元素的宽度和高度,包括边框和 填充(不包括页边距) clientWidth和clientHeight 元素的宽度和高度,包括填充(不包括 边框和边距) 有关示例,请参见 var elm=document.querySelector('div'); document.body.innerHTML+=` clientWidth:${elm.clientWidth}px

是否可以使用dom获取元素outerWidth

Ej:


不,但你可以得到偏移网络宽度,这可能是你想要的

离网宽度离网视野

整个元素的宽度和高度,包括边框填充(不包括页边距)

clientWidthclientHeight

元素的宽度和高度,包括填充(不包括 边框和边距)

有关示例,请参见

var elm=document.querySelector('div');
document.body.innerHTML+=`
clientWidth:${elm.clientWidth}px

scrollWidth:${elm.scrollWidth}px
offsetWidth:${elm.offsetWidth}px`
div{
宽度:200px;
填充:10px;
边框:10px纯金;
利润率:10px;
背景:浅绿色;
}

肖恩为户外运动提供了完美的解决方案()

此外,如果您正在寻找任何或所有jQuery维度获取程序的替代品,请参阅下面我的解决方案

注意:即使在
*{box size:border box}

function 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;
}

应该注意的是,它们并不完全相同。jQuery将为您提供元素的宽度,即使它不在文档中,或者它是隐藏的;而
element.outerWidth
element.clientWidth
如果元素被隐藏,将返回
0
,如果元素不在文档中,则返回
未定义的
。offsetWidth不是交叉浏览器似乎应该使用
元素。getBoundingClientRect()
,因为它在除Chrome以外的浏览器中可用(不同于
offsetWidth
offsetHeight
)。它返回具有
宽度
高度
属性的对象。
function 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;
}