Setting width and height as a percentage in JavaScript

南笙酒味 提交于 2021-01-29 15:57:15

问题


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.


回答1:


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.




回答2:


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%


来源:https://stackoverflow.com/questions/18300408/setting-width-and-height-as-a-percentage-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!