2011-05-30 185 views
0

我已經創建了一個簡單的插件之後tuts +和修改它做我想做的。 它基本上創建了一個「工具提示」,我試圖在一段時間內保持可見狀態,但也允許用戶單擊該塊,以便獲得比工具提示更多的通知。我到目前爲止是在下面,但是當它不自動隱藏...然後點擊關閉工作。任何人都可以發現我在做什麼錯誤/改進?自定義jquery插件bug

$.fn.betterTooltip = function(options){ 

    /* Setup the options for the tooltip that can be 
     accessed from outside the plugin    */ 
    var defaults = { 
     speed: 200, 
     delay: 300, 
     hideAfter:5000 
    }; 

    var options = $.extend(defaults, options); 

    /* Create a function that builds the tooltip 
     markup. Then, prepend the tooltip to the body */ 
    getTip = function() { 
     var tTip = 
     "<div class='tip'>" + 
     "<div class='tipMid'>" + 
     "</div>" + 
     "<div class='tipBtm'></div>" + 
     "</div>"; 
     return tTip; 
    } 
    $("body").prepend(getTip()); 

    /* Give each item with the class associated with 
     the plugin the ability to call the tooltip */ 
    $(this).each(function(){ 

     var $this = $(this); 
     var tip = $('.tip'); 
     var tipInner = $('.tip .tipMid'); 

     var tTitle = (this.title); 
     this.title = ""; 

     var offset = $(this).offset(); 
     var tLeft = offset.left; 
     var tTop = offset.top; 
     var tWidth = $this.width(); 
     var tHeight = $this.height(); 

     /* Delay the fade-in animation of the tooltip */ 
     setTimer = function() { 
      $this.showTipTimer = setInterval("showTip()", defaults.delay); 
     } 
     hideTip=function(){ 
      stopTimer(); 
      tip.hide(); 
     } 
     stopTimer = function() { 
      clearInterval($this.showTipTimer); 
      clearInterval($this.hideTimer); 
     } 

     /* Position the tooltip relative to the class 
      associated with the tooltip    */ 
     setTip = function(top, left){ 
      var topOffset = tip.height()-30; 
      var xTip = (left+60)+"px"; 
      var yTip = (top-topOffset)+"px"; 
      tip.css({ 
       'top' : yTip, 
       'left' : xTip 
      }); 
     } 

     /* This function stops the timer and creates the 
      fade-in animation       */ 
     showTip = function(){ 
      stopTimer(); 
      tip.animate({ 
       "top": "+=20px", 
       "opacity": "toggle" 
      }, defaults.speed); 
     } 
     $(this).ready(function() { 
      tipInner.html(tTitle+'<br />(Click to dismiss)'); 
      setTip(tTop, tLeft); 
      setTimer(); 
      hideTimer=function(){ 
       $this.hideTimer=setInterval("hideTip()",defaults.hideAfter); 
      } 
      hideTimer(); 
     }); 
     $(tip).click(function() { 
       hideTip(); 
     }); 
    }); 
}; 

回答

2

我想你想setTimeoutclearTimeout,而不是你有...Interval版本。前者曾經回擊過一次,而後者則一次次地回傳。

一些提示:

  1. 字符串不要傳遞給setTimeoutsetInterval的代碼運行 - 用一個函數指針。我發現它不太容易出錯,範圍確定也不是問題。
  2. 隱藏mouseleave事件中的提示(無論是來自提示的項目還是提示本身),並在mouseovermouseenter上顯示。這比一直運行javascript更高效。
+0

謝謝你,我已經做出了改變,:-) – zcourts 2011-06-01 19:26:13