日期:2014-05-16  浏览次数:20355 次

关于Javascipt实现隐藏和显示的问题
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style>
#div1 {
width:100px;
height:200px;
background:red;
display:none;
}
</style>
<script>
function ChangColor(){
var oDiv=document.getElementById("div1")
if(oDiv.style.display=="none")
{
oDiv.style.display="block";
}
else
{
oDiv.style.display="none";
}

}
</script>
</head>

<body>
<div id="div1">

</div>
<input type="button" value="提示隐藏" onclick="ChangColor()"/>
</body>
</html>

这是我写的一段代码,点击按钮会交互性的隐藏和显示div1里的内容,但是如果我的代码这样写的话,打开网页,div1首先是隐藏的,点击按钮第一下不会有反应,后面的才会有反应,但是如果我把
#div1 {
width:100px;
height:200px;
background:red;
display:none;
}
换成
#div1 {
width:100px;
height:200px;
background:red;
display:block;
}
再打开网页,点击按钮第一下是有反应的,有了请情况的大牛能解释下不?
js?diplay?if?

------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style>
#div1 {
width:100px;
height:200px;
background:red;
display:none;
}
</style>
<script>
function ChangColor(){
var oDiv=document.getElementById("div1");
var display="";
if(document.defaultView&&document.defaultView.getComputedStyle){
display=document.defaultView.getComputedStyle(oDiv).display;
}else{
display=oDiv.currentStyle.display
}
if(display=="none")
{
oDiv.style.display="block";
}
else
{
oDiv.style.display="none";
}

}
</script>
</head>

<body>
<div id="div1">

</div>
<input type="button" value="提示隐藏" onclick="ChangColor()"/>
</body>
</html>

获取样式没获取到的样子
------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<style>
#div1 {
width:100px;
height:200px;
background:red;
display:none;
}
</style>

<