【问题标题】:JS element offset width returns wrong valueJS元素偏移宽度返回错误值
【发布时间】:2019-01-06 09:01:23
【问题描述】:

我试图获取一个元素的宽度,但是返回的值是错误的

   let container = document.querySelector('.content')
    console.log(container.offsetWidth) //this will log wrong value 1182px instead of 960px

  console.log(getComputedStyle(container).width) //1182px anyway I don't have any idea from where the value comes

我不知道为什么返回的值是错误的

【问题讨论】:

  • 不,虽然使用计算的结果相同
  • this answer。应该使用box-sizing: border-box

标签: javascript containers width


【解决方案1】:

试试这个。这在获得偏移宽度之前对我有用,您可以将宽度设置为

let container = document.querySelector('.content')
container.style.width = "fit-content";
console.log(container.offsetWidth);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多