JS元素偏移宽度返回错误的值

时间:2019-01-06 09:01:23

标签: javascript containers width

我尝试获取元素的宽度,但返回值错误

   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

enter image description here

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

1 个答案:

答案 0 :(得分:0)

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

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