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源碼

設計思路:javascript

  一、採用函數自執行的方法,在獨立的做用域中將方法綁定到jQuery上css

  二、定義構造函數Delay,並在構造函數中初始化timeout(多長時間不動後隱藏鼠標指針),同時在window上綁定mousemove事件,html

    當鼠標移動時,執行mouseDelay方法java

  三、mouseDelay方法中,判斷鼠標的狀態,若是處於隱藏狀態就顯示出來。從新綁定setTimeout,在timeout的時間以後再次隱藏jquery

  四、顯隱鼠標執行使用的是css(cursor:default/none);ide

使用方法:函數

  在使用jQuery選擇器選擇的jQuery對象上調用autohide()方法this

  DEMO:spa

 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>
相關文章
相關標籤/搜索