简体   繁体   中英

getting width of content, not viewport using vanilla JavaScript

I have tried the following and gotten the viewport width:

document.documentElement.clientWidth

and

window.innerWidth

However, what I want to get is the width of the content including overflow, for example if I had an image on the page <img src=".." style="width: 4000px !important;" /> <img src=".." style="width: 4000px !important;" /> . In other words, the entire scrollable width. How would I do this?

Use scrollWidth for the body scrollWidth docs . Also please don't use !important . Only use it as a last resort

 console.log(document.body.scrollWidth) 
  <img src="https://via.placeholder.com/150" style="width: 4000px;" /> 

You can do this with Element.offsetWidth

document.documentElement.offsetWidth

You can read more about offsetWidth here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM