jQuery 入门教程(5): 显示/隐藏内容

jerry JQuery 2015年08月24日 收藏

jQuery的hide()和show()可以用来显示和隐藏内容。比如下面的例子:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JQuery Demo</title>
  6. <script src="scripts/jquery-1.9.1.js"></script>
  7. <script>
  8. $(document).ready(function () {
  9. $("#hide").click(function () {
  10. $("p").hide();
  11. });
  12. $("#show").click(function () {
  13. $("p").show();
  14. });
  15. });
  16. </script>
  17. </head>
  18. <body>
  19. <p>If you click on the "Hide" button, I will disappear.</p>
  20. <button id="hide">Hide</button>
  21. <button id="show">Show</button>
  22. </body>
  23. </html>

20130306001基本语法
$(selector).hide(speed,callback);

$(selector).show(speed,callback);
可选的参数speed 给出显示或隐藏内容的速度,可以使用“slow”,”fast”或者数字代表微秒。
第二个可选参数为回调函数,在显示或隐藏结束时调用。下面代码在1秒钟内隐藏内容:

  1. $("button").click(function(){
  2. $("p").hide(1000);
  3. });

jQuery toggle()方法

使用toggle()方法,可以实现交替显示和隐藏内容,如:

  1. $("button").click(function(){
  2. $("p").toggle();
  3. });

其基本语法如下:

$(selector).toggle(speed,callback);

可选的参数speed 给出显示或隐藏内容的速度,可以使用“slow”,”fast”或者数字代表微秒。
第二个可选参数为回调函数,在显示或隐藏结束时调用