jQuery:动画隐藏字母随机但间隔相等

我有两个问题。

  • 为什么使字母随机消失的动画对所有字母的速度都不一样? 动画不流畅。

  • 如何使动画在另一侧工作? 当我用.hide()隐藏div时,我尝试使其显示为不透明度,这将无效。 我已经尝试了不同的解决方案,但实际上没有什

码:

function wow1 () { var mail1 = $(".mailFirst h2"); var letters = mail1.children(); setInterval(function() { letters.eq(Math.random()*letters.length |0).animate({opacity:0},500); },500); } $(document).ready(wow1); 
 .mailFirst {position: absolute; top: 0; left: 0; color: red;} 
  

@ E - M a i l @

问题

脚本中的问题包括一个主要错误,即您生成的随机数不知道生成的数字将用于选择span并隐藏它并且它需要是一个有效的索引,以及它保留的实际情况在生成可能出现两次的数字时,在这种情况下,它会尝试再次隐藏隐藏的字母,并且尝试找到有效索引的等待时间也不会隐藏它有时需要更少的时间或更多。 这就是隐藏时间不一样的真正原因。

其次,你只是在运行动画,就是它没有停止连续运行的脚本并加载你的浏览器以及setInterrval() ,即使它被最小化或切换,也不知道你的浏览器是否只有怜悯,一旦隐藏所有跨度,您需要停止它。

该怎么办

  1. 选择您要隐藏的元素。

  2. 在var say elemArray使用.toArray()获取数组中的elemArray

  3. 开始生成随机数并validation它是否是elemArray的有效索引,如果不是递归调用它,直到找到范围[0 - elemArray.length]之间的有效索引。

  4. 当你找到一个有效的索引隐藏该索引上的元素并使用splice以这种方式从elemArray中删除该元素时,你将隐藏每个元素一次并进入随机序列

  5. 现在关于动画,请求requestAnimationFrame()

    requestAnimationFrame函数,允许您在JavaScript中创建流畅和流畅的动画,而不必担心使其流畅和流畅。 只需添加一些对requestAnimationFrame调用,您的浏览器就可以完成其余的工作。 而已。 它还有助于控制诸如笔记本电脑/手机/平板电脑进入电池模式等因素并将其性能降低一半。 诸如另一个选项卡关注的因素。 Here阅读更多

  6. 最后,你必须停止动画,所以使用requestAnimationFrame函数的兄弟,即cancelAnimationFrame

看下面我创建了一个演示版,希望它可以帮到你。

 var framesPerSecond = 10; var letters = $(".mailFirst>h2 span"); var elemArray = letters.toArray(); // store your requestAnimatFrame request ID value var requestId; //the animation function function animate() { setTimeout(function() { //save the id returned from the function to use it //for canceling or stopping the animation requestId = requestAnimationFrame(animate); // animating/drawing code goes here hideRandomWord(); //check if there are no more elements left to hide if (!elemArray.length) { stopAnimation(requestId); } }, 2000 / framesPerSecond); } //start animation requestAnimationFrame(animate); //function to hide a character / word function hideRandomWord() { var min = 0; var max = Math.floor(elemArray.length); //The maximum is exclusive and the minimum is inclusive var rand = Math.floor(Math.random() * (max - min)) + min; //if elements array is not empty if (elemArray.length) { //if the generated index is a valid index for the elements array if (typeof elemArray[rand] !== 'undefined') { //animate opacity $(elemArray[rand]).animate({ opacity: 0 }); //remove the element from the elements array elemArray.splice(rand, 1); } else { //call recursively it self if not valid index generated hideRandomWord(); } } } function stopAnimation(requestId) { // use the requestID to cancel the requestAnimationFrame call cancelAnimationFrame(requestId); } 
 .mailFirst { position: absolute; top: 0; left: 0; color: red; } 
  

@ E - M a i l @

第一个问题,即字母隐藏不均匀,是由于随机函数的性质。 它会查找一个随机隐藏的字母,隐藏它并选择另一个字母。 但是随机选择仍然包括已经被隐藏的字母,所以它只是隐藏它们 – 这是一个你看不到的操作所以看起来什么也没发生。 你需要删除数组中的字母,因为它们不再包含在随机选择中。

史蒂夫解释得很好,但这里是代码。

      

@ E - M a i l @