JS点击显示,再次点击隐藏的效果,怎么做?

JavaScript011

JS点击显示,再次点击隐藏的效果,怎么做?,第1张

代码如下:

<html>

<head>

<meta charset="gb2312"> <title>隐藏和显示</title> <style type="text/css"> #thediv {  width:200px  height:100px  line-height:100px  text-align:center  background-color:green } </style> <script type="text/javascript"> function Show_Hidden(obj) {  if(obj.style.display=="block")  {   obj.style.display='none'  }  else  {   obj.style.display='block'  } } window.onload=function() {  var olink=document.getElementById("link")  var odiv=document.getElementById("thediv")  olink.onclick=function()  {   Show_Hidden(odiv)   return false  } } </script> </head> <body> <a href="#" id="link">显示\隐藏切换</a> <div id="thediv" style="display:block">欢迎您</div> </body> </html>

以上代码实现了我们的要求,点击顶部链接可以实现div显示和隐藏的切换。

实现原理:

为链接注册onclick事件处理函数,此处理函数可以判断div的style.display属性值,如果为block则将其设置为none,也就是将div设置为隐藏状态,否则设置为block,也就是将div设置为显示状态,原理大致如此。

需要特别注意的是,在div中,之所以使style="display:block"的目的是让obj.style.display语句能够获取属性值,否则第一次点击无法将div设置为隐藏,大家可以去掉style="display:block"做一下测试,return false语句是为了防止链接的跳转效果。

需要准备的材料分别有:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html,编写问题基础代码。

2、在index.html中的<script>标签,输入js代码:$('button').click(function () {$('#123').css('display', 'block')})。

3、浏览器运行index.html页面,此时点击btn按钮后,div的内容成功被显示了出来。