[英]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.