jQuery-toggle()与toggle(fn,fn)的用法

来源:互联网 发布:seo和sem的区别 编辑:程序博客网 时间:2024/04/30 16:37

toggle()方法的效果就是切换元素的可见状态;即如果元素是可见的,切换为隐藏的;如果元素是隐藏的,切换为可见的。

例子:

$(function(){
 $("#content").toggle();
})

<p id="content" style="display:none">这里原来是隐藏看不到的</p>

当有点击事件时,另一区域可见状态切换可以这么写:

$(document).ready(function(){
  $("#test").click(
  function(){
   $("#content").toggle();
  }
  );
 });

<p id="test"><input type="button" value="点击这里" /></p>
<p id="content" style="display:none">当点击上面的“点击这里“字样,这里的内容将隐藏与显示之间切换</p>

下面说一下toggle(fn,fn)方法的使用,效果是:每次点击后依次调用函数;如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击同一元素时,则触发指定的第二个函数,如果有更多函数,则再次触发,直到最后一个。随后的每次点击都重复对这几个函数的轮番调用。注意这里本身已经有点击触发调用函数的功能,不需要另外.click(fn)了,我一开始操作此函数时就犯了错。

例子:

$(document).ready(function(){
    $("#test").toggle(function(){
     $("#content").hide('slow');
    },function(){
     $("#content").show('fast');
   });
});

<p id="test"><input type="button" value="点击这里" /></p>
<p id="content" style="display:none">当点击上面的“点击这里“字样,这里的内容将隐藏与显示之间切换</p>

<!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>toggle的用法</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".tomato1").click(function(){
$(".tomato2").toggle();
});
});
</script>

</head>
<body>


<p class="tomato1">这里本来是 显示的。</p>

<p class="tomato2" style="display: none">这里本来是隐藏的</p>
<!--切换元素的可见状态。
如果元素是可见的,切换为隐藏的;如果元素是隐藏的,切换为可见的。
-->

 

<script type="text/javascript">
$(document).ready(function(){
    $("#test").toggle(function(){
     $("#content").hide('slow');
    },function(){
     $("#content").show('fast');
   });
});

</script>

<p id="test"><input type="button" value="点击这里" /></p>
<p id="content">当点击上面的“点击这里“字样,这里的内容将隐藏与显示之间切换</p>
</body>
</html>

 

原创粉丝点击