问题
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