第一种方法:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css">
#demo1{width:500px;height:200px;border:5px gray solid;margin:0 auto;display:none;background:red;}
#demo2{width:500px;height:200px;border:5px gray solid;margin:0 auto;display:none;background:white;}
#demo3{width:500px;height:200px;border:5px gray solid;margin:0 auto;display:none;background:black;}
}
</style>
</head>
<body>
<center>
<input type="button" value="显示/隐藏第一个盒子" οnclick="mydiv('demo1')" />
<input type="button" value="显示/隐藏第二个盒子" οnclick="mydiv('demo2')" />
<input type="button" value="显示/隐藏第三个盒子" οnclick="mydiv('demo3')" />
</hr>
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>
</center>
<script language="JavaScript" type="text/JavaScript">
function mydiv(id){
if(document.getElementById){
x= document.getElementById(id);
if(x.style.display =="block"){
x.style.display ="none";
}
else{
x.style.display="block";
}
}
}
</script>
</body>
</html>
_______________________________________________________________
第二种方法:
<!DOCTYPE html>
<html>
<head>
<style>
#main1{width:500px;height:200px;border:2px solid red;}
</style>
</head>
<body>
<p id="main1"></p>
<input type="button" value="隐藏盒子" οnclick="document.getElementById('main1').style.visibility='hidden'" />
<input type="button" value="显示盒子" οnclick="document.getElementById('main1').style.visibility='visible'" />
</body>
</html>
document.getElementById()是JavaScript中的语法通过元素的ID特性来获取元素
例如有入下元素: <input type= "text" id="button1" value="Click Me"/> 那么当调用document.getElementById("button1").Value的时候,返回的就是"Click Me"了
getElementById
语法:obj= document . getElementById ( sID )参数:sID : 必选项。字符串(String)。返回值:obj: 对象(object)根据指定的 id 属性值得到对象。返回 id 属性值等于 sID 的第一个对象的引用。假如对应的为一组对象,则返回该组对象中的第一个。如果无符合条件的对象,则返回 null 。HTML DOM 定义了多种查找元素的方法,除了 getElementById() 之外,还有 getElementsByName() 和 getElementsByTagName()。不过,如果您需要查找文档中的一个特定的元素,最有效的方法是 getElementById()。在操作文档的一个特定的元素时,最好给该元素一个 id 属性,为它指定一个(在文档中)唯一的名称,然后就可以用该 ID 查找想要的元素。实际例子:<html><head><script type="text/javascript">function getValue(){var x=document.getElementById("myHeader")alert(x.innerHTML)}</script></head><body><h1 id="myHeader" οnclick="getValue()">This is a header</h1><p>Click on the header to alert its value</p></body></html>onclick 事件onclick 事件会在对象被点击时发生请注意, onclick 与 onmousedown 不同。单击事件是在同一元素上发生了鼠标按下事件之后又发生了鼠标放开事件时才发生的支持该事件的 JavaScript 对象:
button, document, checkbox, link, radio, reset, submit<html> <body> Field1: <input type="text" id="field1" value="Hello World!"> <br /> Field2: <input type="text" id="field2"> <br /><br /> 点击下面的按钮,把 Field1 的内容拷贝到 Field2 中: <br /> <buttononclick="document.getElementById('field2').value= document.getElementById('field1').value"
>Copy Text</button> </body> </html>