jQuery交互帮助方法 登录

jQuery交互帮助方法

1. hover( over, out ) 

hover函数主要解决在原始javascript中mouseover和mouseout函数存在的问题, 看下面这个示例:

image_thumb_6.png

有两个div(红色区域), 里面分别嵌套了一个div(黄色区域). HTML代码如下:

  <div class="outer" id="outer1">
     Outer 1      <div class="inner" id="inner1">Inner 1</div>
   </div>
   <div class="outer" id="outer2">
     Outer 2      <div class="inner" id="inner2">Inner 2</div>
   </div>
   <div id="console">
</div>

绑定如下事件:

<script type="text/javascript">
     function report(event) {
       $('#console').append('<div>'+event.type+'</div>');
     }
     $(function(){
       $('#outer1')
        .bind('mouseover',report)
        .bind('mouseout',report);
       $('#outer2').hover(report,report);
     });    
</script>


Outer1我们使用了mouseover和mouseout事件,  当鼠标从Outer1的红色区域移动到黄色区域时, 会发现虽然都是在outer1的内部移动, 但是却触发了mouseout事件:

image_thumb_7.png

很多时候我们不希望出现上图的结果,  而是希望只有鼠标在Outer1内部移动时不触发事件, Outer2使用Hover()函数实现了这个效果:

image_thumb_8.png

注意这里的事件名称进入叫做"mouseenter", 离开叫做"mouseleave", 而不再使用"mouseover"和"mouseleave"事件.

有经验的开发人员会立刻想到在制作弹出菜单时, 经常遇到这个问题: 为弹出菜单设置了mouseout事件自动关闭, 但是鼠标在弹出菜单内移动时常常莫名其妙触发mouseout事件让菜单关闭. hover()函数帮助我们很好的解决了这个问题.

2. toggle( fn, fn2, fn3,fn4,... )

toggle函数可以为对象添加click事件绑定函数,  但是设置每次点击后依次的调用函数。

如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击同一元素时,则触发指定的第二个函数,如果有更多函数,则再次触发,直到最后一个。随后的每次点击都重复对这几个函数的轮番调用。

可以使用unbind("click")来删除。

下面的示例演示如何使用toggle函数:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head>
   <title>toggle example</title>
   <link rel="stylesheet" type="text/css" href="css/hover.css">
   <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
   <script type="text/javascript">
       $(function()
       {
           $("li").toggle(              function()
             {
                 $(this).css({ "list-style-type": "disc", "color": "blue" });
             },              function()
             {
                 $(this).css({ "list-style-type": "square", "color": "red" });
             },              function()
             {
                 $(this).css({ "list-style-type": "none", "color": "" });
             }
           );
       })    </script></head><body>
   <ul>
       <li style="cursor:pointer">click me</li>
   </ul>
</body>
</html>


结果是每点击一次"click me"变换一次列表符号和文字颜色.


下一节
<html> <head> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".btn1").click(function(){ $("p").toggle(); }); }); </script> </head> <body> <p>This is a paragraph.</p> <button class="btn1">Toggle</button> </body> </html>
提交 重置代码
章节 评论 笔记 课件
  • 取消 回复 发送
  • 取消 发布笔记 发送