JS实现slideDown()和slideUp()效果
这两天在写一个小Demo,页面顶部需要实现webAPP那种将导航收起,通过按钮点击显示与隐藏的效果。实现过程中也花费时间挺久的,现在单独将这部分拎出来记录一下。废话太多了,直接上代码:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>响应式</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
a{
text-decoration: none;
color: inherit;
}
ul li{
list-style-type: none;
}
header{
width: 100%;
text-align: center;
}
.codeHead{
width: 100%;
height: 70px;
line-height: 70px;
color: #fff;
display: inline-block;
text-align: center;
font-size: 22px;
position: relative;
z-index: 99;
background-color: #7ea6b1;
}
#nav-btn{
height: 20px;
width: 20px;
display: inline-block;
border: 1px solid #fff;
position: absolute;
top: 25px;
right: 30px;
color: #fff;
background-color: #7ea6b1;
}
#nav-list{
width: 100%;
background-color:#7ea6b1;
position: relative;
z-index: 2;
height: 0;
overflow: hidden;
}
#nav-list li{
width: 100%;
color: white;
font-size: 14px;
line-height: 30px;
text-align: center;
border-top: 1px solid #fff;
}
</style>
</head>
<body>
<header>
<nav>
<div class="codeHead">
<div>let's code</div>
<button id="nav-btn">=</button>
</div>
<ul id="nav-list">
<li>首页</li>
<li>Java</li>
<li>ios</li>
<li>Android</li>
<li>php</li>
</ul>
</nav>
</header>
</body>
<script type="text/javascript">
function menu(){
var navList = document.getElementById('nav-list');
console.log(navList);
var navBtn = document.getElementById('nav-btn');
console.log(navBtn);
navBtn.onclick = function(){
var i = 156;
var j = 0;
if(!navList.offsetHeight){
var idOut = setInterval(frameOut, 1);
function frameOut() {
if (j == 156) {
clearInterval(idOut);
} else {
j++;
navList.style.height = j + 'px';
}
console.log("j==155:" + navList.offsetHeight);
}
}else {
var idIn = setInterval(frameIn, 1);
function frameIn() {
if (i == 0) {
clearInterval(idIn);
} else {
i--;
navList.style.height = i + 'px';
}
console.log("i==0:" + navList.offsetHeight);
}
}
console.log("click");
}
console.log("menu.navList.style.height:",navList.offsetHeight);
}
menu();
</script>
</html>
实现过程中遇到的坑:
z-index无效的情况,一共有三种:
- 父标签 position属性为relative;
- 问题标签无position属性(不包括static);
- 问题标签含有浮动(float)属性。
关于div高度
document.style.height只能获取内联样式的元素的高度。
document.offsetHeight获取除margin外的宽和高。比较常用。但是通过其设置div的宽高没设置成功,建议设置高度使用document.style.height。