简体   繁体   English

根据高度和宽度调整div的大小

[英]Resizing a div according to height and width

I'm trying to resize a div according to the height and width of the browser. 我正在尝试根据浏览器的高度和宽度调整div的大小。 The div is supposed to be empty at the beginning and should always mantain a width of 100% and a height of 50% using ONLY javascript. div开头应该是空的,并且只能使用javascript保持100%的宽度和50%的高度。

Here's the code, in this case I used screen.availHeight and screen.availWidth which is fine only in full screen mode. 这是代码,在这种情况下,我使用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> 

Check this fidde I've used window.innerWidth and window.innerHeight to get height and width of view area. 选中此字段,我已使用window.innerWidth和window.innerHeight获取视图区域的高度和宽度。 if you want to use clientWidth and clientHeight you need to set height of HTML and BODY element to 100% so that they consume full height of viewport and 50% height can be calculated from that. 如果要使用clientWidth和clientHeight,则需要将HTML和BODY元素的高度设置为100%,以便它们占用视口的全部高度,并可以从中计算出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> 

The use of JS in this case is redundant. 在这种情况下,使用JS是多余的。 It can be accomplished with the following CSS: 可以使用以下CSS来完成:

html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}
#to-do {
    height: 50%;
    width: 100%;
}

This should work: 这应该工作:

adaptToScreen(document.getElementById('to-do'),100,50); AdaptToScreen(document.getElementById('to-do'),100,50);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM