淡出&文本循环 - jQuery

时间:2012-08-22 01:37:14

标签: jquery

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

2 个答案:

答案 0 :(得分:43)

你可以这样做:

CSS:

.quotes {display: none;}​

HTML:

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

使用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();

})();​

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

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

答案 1 :(得分:1)

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

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

然后必须在上述<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>