简体   繁体   English

如何使一个函数在jquery中重复?

[英]How make make a function repeat itself in jquery?

Let's say for example I want to make a function that makes a div fadeOut & fadeIn and repeat itself every 10 seconds. 比方说,我想创建一个函数,使div fadeOutfadeIn并每10秒重复一次。 In jQuery. 在jQuery中。 This is my current code. 这是我目前的代码。

window.setInterval(function(){
    $("leftEye").fadeOut("slow");
}, 5000);

CSS animation would seem more appropriate in this case - not least of all because it's hardware accelerated. 在这种情况下,CSS动画似乎更合适 - 尤其是因为硬件加速了。 You can create keyframes, then set them to animate over the period of 5 seconds, repeating infinitely. 您可以创建关键帧,然后将它们设置为在5秒的时间内动画,无限重复。

 @keyframes fade { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } } .inifinte-fader { opacity: 1; animation: fade 5s infinite; } 
 <div class="inifinte-fader">Foo bar fizz buzz</div> 

If you want to use your approach with jQuery, you can just use fadeToggle instead of fadeOut . 如果你想在jQuery中使用你的方法,你可以使用fadeToggle而不是fadeOut

// toggle the fade effect for #leftEye every 10 seconds
window.setInterval(function(){
   $("leftEye").fadeToggle("slow");
}, 10000); // 10000 milliseconds

This will make sure to appropriately toggle the fade effect every ~10s. 这将确保每隔~10秒适当地切换淡入淡出效果。

An arguably better approach would be to use CSS, as demonstrated by Rory McCrossan , especially instead of using jQuery for animation. 可以说更好的方法是使用CSS,正如Rory McCrossan所证明的那样 ,特别是不使用jQuery来制作动画。

The reason is that the browser's rendering engine can usually perform the animations more efficiently using CSS (it can optimize things ahead of time) whereas animating using JavaScript sometimes cannot be optimized ahead of time. 原因是浏览器的渲染引擎通常可以使用CSS更有效地执行动画(它可以提前优化事物),而使用JavaScript动画有时无法提前优化。 It's also easier and more expressive to write animation logic using CSS compared to using JS to manually perform various calculations such as transitioning the height or opacity over time. 与使用JS手动执行各种计算(例如随时间转换高度或不透明度)相比,使用CSS编写动画逻辑也更容易且更具表现力。

Now, using jQuery for this animation is actually even more expressive than CSS (since its 1 line of code) but if performance is important using CSS definitely beats jQuery. 现在,在这个动画中使用jQuery实际上比CSS更具表现力(因为它的1行代码)但是如果性能很重要,那么使用CSS肯定胜过jQuery。

Its important to note however that well-optimized JavaScript (not jQuery) is often just as fast if not faster than CSS animations. 但值得注意的是,经过充分优化的JavaScript(不是jQuery)通常与CSS动画相比速度更快。

Here's a good article comparing animation using CSS vs JS and jQuery 这是一篇很好的文章比较使用CSS与JS和jQuery的动画

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM