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

js控制div点击隐藏显示

2017-03-06 14:07 766 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/"/>
<title>点击切换</title>
<style type="text/css">
#thediv {
width: 200px;
height: 50px;
background: #ccc;
display: none;
}
</style>
<script type="text/javascript">
window.onload = function () {
var obt = document.getElementById("bt");
var odiv = document.getElementById("thediv");

function getStyle(obj, attr) {  //  谁的      那个属性
if (obj.currentStyle)  // ie 等
{
return obj.currentStyle[attr];
}
else {
return window.getComputedStyle(obj, null)[attr];  // w3c 浏览器
}
}
//console.log(getStyle(odiv, 'display'));
obt.onclick = function () {
//获取的样式需要写在点击事件里面,写在外面只能获取一次,不能动态获取,
if (getStyle(odiv, 'display') == "none") {
odiv.style.display = "block";
obt.value = "隐藏模块";
}
else {
odiv.style.display = "none";
obt.value = "显示模块";
}
}
}
</script>
<body>
<input type="button" id="bt" value="显示模块"/>
<div id="thediv"></div>
</body>
</html>

以上为第一种

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/"/>
<title>点击切换</title>
<style type="text/css">
#thediv {
width: 200px;
height: 50px;
background: #ccc;
display: none;
}
</style>
<script type="text/javascript">
window.onload = function () {
var obt = document.getElementById("bt");
var odiv = document.getElementById("thediv");
obt.onclick = function () {
if (odiv.style.display== "block") {
//第一判断时将none改为block即可避免第一次点击无效的问题
odiv.style.display = "none";
obt.value = "显示模块";
}
else {
odiv.style.display = "block";
obt.value = "隐藏模块";
}
}
}
</script>
<body>
<input type="button" id="bt" value="显示模块"/>
<div id="thediv"></div>
</body>
</html>以上为第二种

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style type="text/css">
#thediv{
width:200px;
height:50px;
background:#ccc;
}
</style>
<script type="text/javascript">
window.onload=function(){
var obt=document.getElementById("bt");
var odiv=document.getElementById("thediv");
obt.onclick=function(){
if(odiv.style.display=="none"){
odiv.style.display="block";
obt.value="隐藏模块";
}
else{
odiv.style.display="none";
obt.value="显示模块";
}
}
}
</script>
<body>
<input type="button" id="bt" value="显示模块"/>
<div id="thediv" style="display:none"></div>
</body>
</html>以上为第三种
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: