gpt4 book ai didi

javascript - 为什么不能在 javascript 中使用 % 更改最大高度?

转载 作者:太空宇宙 更新时间:2023-11-04 14:32:59 25 4
gpt4 key购买 nike

我正在尝试构建一个带有汉堡包图标的响应式菜单。我希望菜单列表可以滑入和滑出,没有 jquery - 只有纯 javascript。

HTML:

<div id="animation">  
</div>
<button id="toggle">Toggle</button>

CSS:

div {
width: 300px;
height: 300px;
background-color: blue;
}

Javascript:

var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback){
var inter = -1, start = 100, end = 0;
if(type==true){
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function(){
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if(start == end){
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function(){
animate(hidden, function(){
hidden = (hidden == false) ? true : false;
});
}

div.style.maxHeight = "50%";

最佳答案

问题是元素中的比例 height 需要父元素的固定高度,而您没有为任何父元素提供固定的 height 因为对于 maxHeight 属性也是 % 以父元素的百分比定义最大高度

您必须将您的 div 放在具有固定高度 的父容器中,这是您的工作代码:

var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback) {
var inter = -1,
start = 100,
end = 0;
if (type) {
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function() {
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function() {
animate(hidden, function() {
hidden = !hidden ;
});
}

div.style.maxHeight = "50%";
#animation {
width: 300px;
height: 300px;
background-color: blue;
}
#parent {
width: 500px;
height: 500px;
}
<div id="parent">
<div id="animation">
</div>
<button id="toggle">Toggle</button>
</div>

注意:

如评论中所述,您的 JavaScript 代码中有一些语句需要调整:

if(type==true) can be written as if(type).

hidden = (hidden == false) ? true : false; can be shortened to hidden = !hidden

关于javascript - 为什么不能在 javascript 中使用 % 更改最大高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com