我正在尝试根据浏览器的高度和宽度调整 div 的大小。 div 在开始时应该是空的,并且应该仅使用 javascript 始终保持 100% 的宽度和 50% 的高度。
这是代码,在本例中我使用了 screen.availHeight 和 screen.availWidth ,仅在全屏模式下才有效。
/* pw stand for width percentage
ph for height percentage */
var adaptToScreen = function(el,pw,ph){
var screenW = screen.availWidth;
var screenH = screen.availHeight;
var w = screenW*(pw/100);
var h = screenH*(ph/100);
el.style.height=h+"px";
el.style.width=w+"px";
};
adaptToScreen(toDoList,100,50);
<div id="to-do"></div>
最佳答案
检查这个fidde 我使用 window.innerWidth 和 window.innerHeight 来获取 View 区域的高度和宽度。 如果你想使用 clientWidth 和 clientHeight ,你需要将 HTML 和 BODY 元素的高度设置为 100%,以便它们占用视口(viewport)的整个高度,并可以从中计算出 50% 的高度。
/* pw stand for width percentage
ph for haight percentage */
var adaptToScreen = function(el,pw,ph){
//var screenW = document.body.clientWidth;
//var screenH = document.body.clientHeight;
var screenW = window.innerWidth;
var screenH = window.innerHeight;
var w = screenW*(pw/100);
var h = screenH*(ph/100);
el.style.height=h+"px";
el.style.width=w+"px";
};
var toDoList = document.getElementById('to-do');
adaptToScreen(toDoList,100,50);
<div id="to-do"></div>
关于javascript - 根据高度和宽度调整 div 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631090/