【发布时间】:2017-11-10 23:36:43
【问题描述】:
Exclaimer,这主要是 sn-p 代码,因为我不知道如何解释这一点。请不要讨厌:3
jQuery 代码应该为“#dd.show”设置“max-height”属性。那么有人可以告诉我为什么这不起作用:
$("#btn").on("click", function() {
$("#dd").toggleClass("show");
});
var dv = document.getElementById("dd");
var item = dv.getElementsByTagName("A");
$("#dd.show").css("max-height", item[0].offsetHeight * item.length + "px");
body {
margin: 10px;
}
#btn {
background-color: red;
color: black;
border: none;
outline: none;
width: 100px;
height: 100px;
font-size: 20px;
-webkit-transition: all .4s ease;
transition: all .4s ease;
}
#btn:hover {
background-color: black;
color: white;
border-radius: 52.5px;
}
#dd {
opacity: 0;
max-height: 0;
width: 200px;
position: relative;
overflow: hidden;
-webkit-transition: all 1s ease;
transition: all 1s ease;
}
#dd.show {
opacity: 1;
}
#dd.show:hover {
border-radius: 15px;
}
#dd a {
background-color: red;
color: black;
padding: 16px 16px;
text-align: center;
text-decoration: none;
display: block;
font-size: 20px;
-webkit-transition: all .4s ease;
transition: all .4s ease;
}
#dd a:hover {
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">press me</button>
<div id="dd">
<a href="#">press me 1</a>
<a href="#">press me 2</a>
<a href="#">press me 3</a>
<a href="#">press me 4</a>
</div>
这就是它应该的样子。我唯一改变的是删除 .css JQuery 并手动添加“max-height”:
$("#btn").on("click", function() {
$("#dd").toggleClass("show");
});
body {
margin: 10px;
}
#btn {
background-color: red;
color: black;
border: none;
outline: none;
width: 100px;
height: 100px;
font-size: 20px;
-webkit-transition: all .4s ease;
transition: all .4s ease;
}
#btn:hover {
background-color: black;
color: white;
border-radius: 52.5px;
}
#dd {
opacity: 0;
max-height: 0;
width: 200px;
position: relative;
overflow: hidden;
top: 10px;
-webkit-transition: all 1s ease;
transition: all 1s ease;
}
#dd.show {
opacity: 1;
max-height: 225px;
}
#dd.show:hover {
border-radius: 37.5px;
}
#dd a {
background-color: red;
color: black;
padding: 16px 16px;
text-align: center;
text-decoration: none;
display: block;
font-size: 20px;
-webkit-transition: all .4s ease;
transition: all .4s ease;
}
#dd a:hover {
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">press me</button>
<div id="dd">
<a href="#">press me 1</a>
<a href="#">press me 2</a>
<a href="#">press me 3</a>
<a href="#">press me 4</a>
</div>
【问题讨论】:
-
您是否做过任何调试工作(例如添加
console.log()调用)以查看item[0].offsetHeight和item.length是什么?该元素确实获得了一个max-height值集。此外,混合使用 jQuery 和 DOM API 有点令人困惑且容易出错。 -
您在单击按钮时动态添加“显示”类。但是您正试图在其他某个时间向“show”类添加样式(此时“show”类不存在)。在点击事件中更改/添加 css。
-
问题是,即使我写“100px”而不是“item[0].offsetHeight * item.length + 'px'”,它仍然给出相同的结果。没有最大高度。
标签: javascript jquery html css