javascript实现Div层的动态显示或隐藏

发布时间:2020-09-18编辑:脚本学堂
当在web页面中使用select控件来显示div的显示与隐藏,可以借助setAttribute方法,实现动态的显示与隐藏,本文给出一个具体的例子,供大家学习参考。

示例代码:

<html>
<title>通过选择项显示不同的结果-www.jb200.com</title>
<head>
<script type="text/javascript">
function showdiv()
{
 var doc=document;
 var citytext=doc.getElementById("city").value;
 var div1=doc.getElementById("div1");
 var div2=doc.getElementById("div2");
 var div3=doc.getElementById("div3");
 switch (citytext)
 {
  case "广州":      
      div1.setAttribute("style","display");   
   div2.setAttribute("style","display:none");
   div3.setAttribute("style","display:none");
   doc.getElementById("text1").value=citytext;
      break;
  case "南昌":
      div1.setAttribute("style","display:none");
   div2.setAttribute("style","display");
   div3.setAttribute("style","display:none");
   doc.getElementById("text2").value=citytext;
   break;
  case "沈阳":
      div1.setAttribute("style","display:none");
   div2.setAttribute("style","display:none");
   div3.setAttribute("style","display");
   doc.getElementById("text3").value=citytext;
   break;
 }
}
</script>
</head>
<body>
<select title="城市" id="city" onchange="showdiv()">
<option selected value="广州">广州</option>
<option value="南昌">南昌</option>
<option value="沈阳">沈阳</option>
</select>
<div  id="div1" style="display:none"  >您选择了广东的省会<input type="text" id="text1" value=""/></div>
<div  id="div2" style="display:none"  >您选择了江西的省会<input type="text" id="text2" value=""/></div>
<div  id="div3" style="display:none"  >您选择了辽宁的省会<input type="text" id="text3" value=""/></div>
</body>
</html>