jQuery UI--jquery-autohide解读

 1 // jQuery Autohide v1.0.2
 2 // (c) 2014 Alex Taujenis
 3 // MIT License
 4 
 5 (function($) {
 6   return $.fn.autohide = function(opts) {
 7     var Delay;
 8     Delay = (function() {
 9       Delay.prototype.timeout = 1000;
10 
11       function Delay(el, opts) {
12         this.el = el;
13         if ((opts != null) && ("timeout" in opts)) {
14           this.timeout = parseInt(opts["timeout"]);
15         }
16         $(window).mousemove(((function(_this) {
17           return function() {
18             return _this.mouseDelay();
19           };
20         })(this)));
21         this;
22       }
23 
24       Delay.prototype.mouseDelay = function() {
25         if (!this.shown) {
26           this.showMouse();
27         }
28         window.clearTimeout(this.mouse_timeout);
29         this.mouse_timeout = window.setTimeout(((function(_this) {
30           return function() {
31             return _this.hideMouse();
32           };
33         })(this)), this.timeout);
34       };
35 
36       Delay.prototype.showMouse = function() {
37         this.el.css("cursor", "default");
38         this.shown = true;
39       };
40 
41       Delay.prototype.hideMouse = function() {
42         this.el.css("cursor", "none");
43         this.shown = false;
44       };
45 
46       return Delay;
47 
48     })();
49     new Delay(this, opts);
50     return this;
51   };
52 })(jQuery);
jQuery-autohide源码

设计思路:

  1、采用函数自执行的方法,在独立的作用域中将方法绑定到jQuery上

  2、定义构造函数Delay,并在构造函数中初始化timeout(多长时间不动后隐藏鼠标指针),同时在window上绑定mousemove事件,

    当鼠标移动时,执行mouseDelay方法

  3、mouseDelay方法中,判断鼠标的状态,如果处于隐藏状态就显示出来。重新绑定setTimeout,在timeout的时间之后再次隐藏

  4、显隐鼠标执行使用的是css(cursor:default/none);

使用方法:

  在使用jQuery选择器选择的jQuery对象上调用autohide()方法

  DEMO:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4   <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
 5   <script src="../src/jquery.autohide.js" type="text/javascript"></script>
 6   <style> body {margin: 0px;} </style>
 7 
 8   <script type="text/javascript">
 9     $(document).ready(function(){
10       $("img").autohide();
11     });
12   </script>
13 
14 </head>
15 <body>
16   <img src="hubble_ultra_deep_field.jpg">
17 </body>
18 </html>

 

 

posted @ 2014-04-16 09:18  charling  阅读(1224)  评论(0编辑  收藏  举报