JS综合应用1: 展开和收起页面中的部分内容。
程序员文章站
2022-06-19 16:48:07
...
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
ul{
margin:0px;
padding:0px;
}
ul li{
background-color:aliceblue;
font-family:微软雅黑;
list-style-type:none;
line-height:45px;
margin-bottom:2px;
font-size:larger;
}
ul li span {
padding:20px;
}
ul li div {
background-color:antiquewhite;
height:400px;
margin:0px;
padding:0px;
}
</style>
<script type="text/javascript">
window.onload = function () {
//方法测试按钮
//var btn = this.document.getElementById('btntest');
//btn.onclick = function () {
// if (btn.value == '合上') {
// ShowDiv(document.getElementById('div1'), 0);
// window.setTimeout(function () { btn.value = '打开'; }, 2 * 1000);
// }
// else if (btn.value = '打开') {
// ShowDiv(document.getElementById('div1'), 400);
// window.setTimeout(function () { btn.value = '合上'; }, 2 * 1000);
// }
//};
//1.获取所有li元素
var liObjs= this.document.getElementsByTagName('li');
//2.给所有span元素注册onclick事件
for (var i = 0; i < liObjs.length; i++) {
liObjs[i].onclick = function () {
//拿到当前li元素下的div
var divObj=GetLiChildDIV(this);
//4.判断状态,调用展开和关闭方法
//判断当天标签状态,合上的话打开
if (divObj.offsetHeight == 0) {
ShowDiv(divObj, 400);
}
//打开时,合上
else {
ShowDiv(divObj, 0);
}
};
}
//3.构建动画展开和关闭方法
///展开和合上层的方法 divObj层对象,ShowedHeight最后展开的高度
function ShowDiv(divObj,ShowedHeight) {
//1.获得高度
var height = divObj.offsetHeight;
//2.设置显示状态
divObj.style.display = 'block';
//3.逐渐增加高度
var intervalId = window.setInterval(function () {
if (ShowedHeight==0) {
height -= 5;
var b = function () { return height < ShowedHeight };
}
else {
height += 5;
var b = function () { return height > ShowedHeight };
}
if (b()) {
//4.到达指定高度,
divObj.style.height = ShowedHeight + 'px';
//停止计时器
window.clearInterval(intervalId);
}
else {
divObj.style.height = height + 'px';
}
}, 20)
}
//获得li标签下的子元素div
function GetLiChildDIV(liObj) {
//获取li下的所有子元素
var children = liObj.children;
//遍历子元素,当元素是DIV时,返回这个元素
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === 'DIV') {
var liChildDiv = children[i];
return liChildDiv;
}
}
}
};
</script>
</head>
<body>
<!-- <input type="button" name="name" value="合上" id="btntest"/> 测试按钮 -->
<ul>
<li>
<span>Visual Studio开发工具</span>
<div></div>
</li>
<li>
<span>Visual Studio开发工具</span>
<div></div>
</li>
<li>
<span>Visual Studio开发工具</span>
<div></div>
</li>
</ul>
</body>
</html>
上一篇: 内涵吃货
下一篇: 草根SEOer需要熟知的8大基础知识