简体   繁体   中英

Setting width and height as a percentage in JavaScript

Here is my JavaScript code:

a.width = a.width ? a.width : 640;
a.height = a.height ? a.height : 360;

How can I make the 640px and 360px percentages instead? I want them both to be 70% of the windows size.

If the container of the element have sizing specified already, then you can simply use percentages in CSS. For instance:

.#my-el {
    width: 70%;
    height: 70%;
}

<div id="my-el"></div>

However, if you have to use JavaScript for some reason, you could do something like:

el.style.width = Math.round(document.documentElement.clientWidth * .70) + 'px';

You may have to use a more complex approach to determine the viewport size for cross-browser support however, but this question was already answered.

percentage is a relative value.

you need to have relative value like screenWidth (for suppose) 1240px so that you will get percentage of that value.

Example

var pixels = 100;
var screenWidth = window.screen.width;
var percentage = ( screenWidth - pixels ) / screenWidth ; // 0.92%

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