简体   繁体   中英

problem with converting Pixel to Viewport units using Javascript

I want to convert px to the viewport units ( vh and vw ). So I used these with no success?

var newWidth = yourElement.outerWidth / document.documentElement.clientWidth *100;
var newHeight = yourElement.outerHeight / document.documentElement.clientHeight *100;

I just get NaN .

I put my calculation in a timeout to be sure I'm selecting the element only when it's rendered.

How can I convert px to viewport units correctly?

yourElement.offsetWidth should work for you Check out this answer to identify the sizes properly: How do I retrieve an HTML element's actual width and height?

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