您的位置:首页 > Web前端 > CSS

JS通过操作Element的Css来实现隐藏和显示(本示例只有隐藏)

2016-12-15 15:47 876 查看
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Collapsed Form Elements</title>
<style>
.label{
width: 400px;
margin: 10px 0 0 0;
padding: 10px;
background-color: #ccccff;
text-align: center;
border: 1px solid #ccccff;
}
.elements{
border: 1px solid #ccccff;
padding: 10px;
border: 1px solid #ccccff;
width: 400px;
}
button{
margin: 20px;
}
</style>
</head>
<body>
<form>
<div>
<div id="section1" class="label">
<p>Checkboxes</p>
</div>
<br id="section1b" class="elements">
<input type="checkbox" name="box1"/> - box one </br>
<input type="checkbox" name="box1"/> - box one </br>
<input type="checkbox" name="box1"/> - box one </br>
<input type="checkbox" name="box1"/> - box one </br>
<input type="checkbox" name="box1"/> - box one </br>
</div>
</div>
<div>
<div id="section2" class="label">
<p>Buttons</p>
</div>
<div class="elements">
<input type="radio" name="box1"/> - box one </br>
<input type="radio" name="box1"/> - box one </br>
<input type="radio" name="box1"/> - box one </br>
<input type="radio" name="box1"/> - box one </br>
<input type="radio" name="box1"/> - box one </br>
<button>Submit</button>
</div>
</div>
</form>
<script type="text/javascript">

/**
* Css Visibility属性来隐藏和显示消息
*
* msg.style.hidden = "visible";   //显示
* msg.style.hidden = "hidden";    //隐藏,但占用页面空间
*
* 或者CSS 的 display属性
* msg.style.display = "block";  //显示
* msg.style.display = "none";   //从显示状态删除
*
* display的4个属性
* none: 该元素从显示中删除
* block:元素当做一个块级元素来处理,在其前后都有换行
* inline-block: 元素内容像一个块级元素一样格式化,然后向内联内容一样排列
* inherit:(默认的显示),并且执行display属性继承至该元素的父节点
*
*
* @type {NodeList}
*/

var elements = document.getElementsByTagName("div");

//折叠起所有的区段
for(var i = 0; i <elements.length; i++){
if(elements[i].className = "elements"){
elements[i].style.display = "none";
}else if(elements[i].className == "label"){
elements[i].onclick = switchDisplay;
}
}

//根据状态折叠或展开
function switchDisplay(){
var parent = this.parentNode;
var target = parent.getElementsByTagName("div")[1];

if(target.style.display == "none"){
target.style.display = "block";
}else{
target.style.display = "none";
}
return false;
}
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: