2012-06-25 75 views
0

我有一个提示的HTML列表,并且该列表中的每个元素都隐藏在页面加载中,然后我尝试在特定时间后淡出3个随机提示,但是提示会在不同时间消失,相同的时间安排,任何想法为什么发生这种情况?JavaScript淡入淡出时间

这里是我的源:

<script type="text/javascript"> 
    this.randomtip = function() { 
     var pause = 4000; 
     var length = $("#tips li").length; 
     var temp = -1; 

     this.getRan = function() { 
      // get the random number 
      var ran = Math.floor((Math.random() * length) + 1); 

      return ran; 
     }; 
     this.show = function() { 
      $("#tips li").fadeOut(800); 
      $("#tips li:nth-child(" + getRan() + ")").delay(1000).fadeIn(800); 
      $("#tips li:nth-child(" + getRan() + ")").delay(1000).fadeIn(800); 
      $("#tips li:nth-child(" + getRan() + ")").delay(1000).fadeIn(800); 
     }; 

     show(); setInterval(show, pause); 

    }; 

    $(document).ready(function() { 
     $("#tips li").hide(); 
     randomtip(); 
    }); 
</script> 

回答

1

这是你的脚本的一个固定的版本:

http://jsfiddle.net/thinkingsites/WPsN7/17/

你的问题如下:

  1. 上的异步法兹工作,所以你基本上淡出一切发生在同一时间。由于时机并不完美,他们很快就失去了同步。
  2. 你的随机方法不能保证它会加载唯一的项目。这可以给同一个元素多次提供相同的命令。

为了解决这个问题,我使用了jQuery deferreds,一个内置的jQuery动画功能。这就是.promis()。done()是。它比使用更具功能.fade(间隔,回调)它确保回调不会触发,直到先前的命令完成。这消除了setInterval的需要,如果控制不好,可能会导致问题。由于jQuery内置了这个功能,所以不是必须的。

0

使用发表“思想网站”代码后,一切似乎是好的,但旧版本的Internet Explorer不支持“的indexOf”所以下面是我的这确实在Internet Explorer中的旧版本以及Chrome和Firefox工作的代码修改后的版本:

<script type="text/javascript"> 
    var randomtip = function() { 
    var pause = 4000; 
    var length = $("#tips li").length; 
    var temp = -1; 

    this.getRan = function() { 
     // get the random number 
     var result = []; 
     while (result.length < 3) { 
      var r = Math.round((Math.random() * (length - 1))); 
      if (!contains(result, r)) { 
       result.push(r); 
      } 
     } 
     return result; 
    }; 

    var fadeout = function() { 
     $("#tips li").delay(1500).fadeOut(800).promise().done(fadein); 
    }; 

    var fadein = function() { 
     var ran = getRan(); 
     $("li:eq(" + ran[0] + "),li:eq(" + ran[1] + "),li:eq(" + ran[2] + ")", "#tips").delay(1000).fadeIn(800).promise().done(fadeout); 
     }; 

     fadein(); 
    }; 

    $(document).ready(function() { 
     $("#tips li").hide(); 
     randomtip(); 
    }); 

    function contains(a, obj) { 
     var i = a.length; 
     while (i--) { 
      if (a[i] === obj) { 
       return true; 
      } 
     } 
     return false; 
    } 
</script>