自定义jquery插件bug

问题描述:

我已经创建了一个简单的插件之后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(); 
     }); 
    }); 
}; 

我想你想setTimeoutclearTimeout,而不是你有...Interval版本。前者曾经回击过一次,而后者则一次次地回传。

一些提示:

  1. 字符串不要传递给setTimeoutsetInterval的代码运行 - 用一个函数指针。我发现它不太容易出错,范围确定也不是问题。
  2. 隐藏mouseleave事件中的提示(无论是来自提示的项目还是提示本身),并在mouseovermouseenter上显示。这比一直运行javascript更高效。
+0

谢谢你,我已经做出了改变,:-) – zcourts 2011-06-01 19:26:13