簡體   English   中英

使用 window 調整大小動態更改 div 高度

[英]Dynamically change div height with window resize

我想在調整 window 大小時更改 div 的高度。 我知道可以使用 css 來完成height:100%; 但這對我需要的不起作用。 我想在沒有 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 的高度以匹配內部 window 高度(以像素為單位)。

謝謝你。

window.innerheight應該是window.innerHeight (大寫H )。 請注意,IE在IE9之前不支持它。

另請注意,您在此處將元素與數字進行比較:

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

您可能希望從left獲得高度,因為該條件永遠不會成立。

請參閱jsfiddle jsfiddle

嘗試使用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 將限制更新(默認情況下更新將在調整大小時每 20 毫秒觸發一次)。 請注意,您需要更新 updateHeight arguments 和.selector以匹配您的 div。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM