通过调整窗口大小动态更改div高度



我想在调整窗口大小时更改div的高度。我知道使用height:100%;可以用css完成,但这不适用于我需要的内容。我想在没有JQuery或任何其他框架的纯javascript中实现这一点。

以下是我所做的:

<div id="left">
<div id="inner">
</div>
</div>

CSS

#left{
margin-top:40px;
width:200px;
height:576px;
background:white;
}
#inner{
height:100%;
overflow-y:scroll;
}

JAVASCRIPT

window.onload=
window.onresize=function(){
var left=document.getElementById('left');
var window_height = window.innerheight;
if ( window_height > 600px ) { left.style.height = document.body.offsetHeight
+"px";    } 
else { } 
} 

id为left的div必须具有相同的边距。我只是想更改div的高度以匹配内部窗口的高度(以px no%为单位)。

谢谢。

window.innerheight应为window.innerHeight(大写H)。请注意,IE在IE9之前不支持它。

还要注意,您正在将元素与此处的数字进行比较:

if ( left < window_height )
//   ^--- element

您可能想从left中获得高度,因为这个条件永远不会成立。

请参阅jsfiddle jsfiddler

尝试使用console.log来了解您处理的值或对象的类型

window.onload = window.onresize = function () {
    var left = document.getElementById('left');
    var window_height = window.innerHeight;
    console.log(left.offsetHeight);
    console.log(window_height);
    if (left.offsetHeight < window_height) {
        left.style.height = window_height + "px";
    } else {}
}

首先设置100%以知道确切的高度编号,然后重新指定高度。

更新代码更新jsfiddle

window.onload = window.onresize = function () {
    var left = document.getElementById('left');
    console.log(left.offsetHeight);
    var window_height = window.innerHeight;
    if (left.offsetHeight < window_height) {
        left.style.height = '100%';    
        left_height=left.offsetHeight;
        console.log(left_height);
        left.style.height = left_height + "px";
    } else {}
};

对于那些寻找使用基于超时的去抖动的老式解决方案的人,以下是您可以做的:

function debounce(func, wait = 20, immediate = true) {
  let timeout;
  return function() {
    const context = this,
      args = arguments;
    const later = function() {
      timeout = null;
      if (!immediate) { func.apply(context, args); }
    };
    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) { func.apply(context, args); }
  };
}
function updateHeight(div, height) {
  div.style.height = `${height}px`;
}
window.addEventListener('resize', debounce(() => {
  const div = document.querySelector('.selector');
  updateHeight(div, 50);
}));

Debounce将抑制更新(默认情况下,在调整大小期间,更新将每20ms启动一次)。请注意,您需要更新updateHeight参数和.selector以匹配您的div。

最新更新