淡入淡出文本循环 - jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12065273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:15:54  来源:igfitidea点击:

Fade in & out text loop - jQuery

jquery

提问by Tyler Almond

I have two quotes wrapped in H2 tags that I want to fade in and out using jQuery. When the page loads I want the first quote to fade in, delay for a few seconds and fade out then the next quote to do the same. I would like it to continue to loop through the two quotes. Any help would be greatly appreciated.

我有两个引号包裹在 H2 标签中,我想使用 jQuery 淡入淡出。当页面加载时,我希望第一个引用淡入,延迟几秒钟然后淡出然后下一个引用做同样的事情。我希望它继续循环遍历这两个引号。任何帮助将不胜感激。

回答by jfriend00

You could do it like this:

你可以这样做:

CSS:

CSS:

.quotes {display: none;}?

HTML:

HTML:

<h2 class="quotes">first quote</h2>
<h2 class="quotes">second quote</h2>?

Javascript:

Javascript:

// code gets installed at the end of the body (after all other HTML)
(function() {

    var quotes = $(".quotes");
    var quoteIndex = -1;

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(2000)
            .delay(2000)
            .fadeOut(2000, showNextQuote);
    }

    showNextQuote();

})();?

Working demo: http://jsfiddle.net/jfriend00/n4mKw/

工作演示:http: //jsfiddle.net/jfriend00/n4mKw/

This code will work for any number of quotes you have, not just two. If you have content after the quotes, you will likely want to fix the size of the container the quotes are in so that it doesn't change size as you go from one quote to the next (causing the other page contents to jump around).

此代码适用于您拥有的任意数量的引号,而不仅仅是两个。如果您在引号之后有内容,您可能希望固定引号所在容器的大小,以便在您从一个引号转到下一个引号时它不会改变大小(导致其他页面内容跳转) .

回答by Kudzai

This is what you need to get the above script working. First you need to reference the apropriate JQuery Framework, so add this scripttag either in the <head>section, or at the end of the <body>tag, after all other elements:

这是使上述脚本正常工作所需要的。首先,您需要引用适当的 JQuery 框架,因此在所有其他元素之后,在该部分或标记末尾添加此脚本标记:<head><body>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">

Then the main JavaScript MUST go be loaded after the aforementioned <script>tag:

然后必须在上述<script>标签之后加载主要的 JavaScript :

<script type="text/javascript">
(function() {

    var quotes = $(".quotes");
    var quoteIndex = -1;

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(2000)
            .delay(2000)
            .fadeOut(2000, showNextQuote);
    }

    showNextQuote();

})();
</script>