Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - JQuery text rotator

I am trying to create a simple jquery text rotator: I have a span in which text should fade in and out. There are similar questions here on stackoverflow but I can't apply their solutions to my situation Here is what I wrote so far and I was wondering why this code doesn't work:

var i=0;
function rotate(spanid,w1,w2,w3){
  var myspan = "#"+spanid;
  var words = [w1,w2,w3];
  $(words[i]).appendTo(myspan).fadeIn(2000).delay(2000).fadeOut(2000);
  i==words.length? i=0:i++;
  rotate(spanid,w1,w2,w3);    
  }

Is the approach to the problem correct? Why isn't this code working? Thank you all in advance!

EDIT The code isn't working as nothing is showing up. Here is the html section relative to the function:

<p>Blah blah blah <span id="rotate"></span> blah blah blah </p>
<script>
$(rotate("rotate","word1","word2","word3"));
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, i've had a quick play and expanded it a little for you..

JS Fiddle: http://jsfiddle.net/4k3zfv5f/

    function rotate(sID,aWords, iIndex){
        $("#"+sID).html(aWords[iIndex]).fadeIn(1000, function() {   
            iIndex==(aWords.length-1)? iIndex=0:iIndex++;           
            $("#"+sID).fadeOut(1000, function() {                   
                rotate(sID,aWords,iIndex);                          
            }); 
        });
    }



    rotate("test1",["Hello", "World", "Foo"], 0);
    rotate("test3",["John", "Bob", "Billy", "Mike", "Larry"], 0);

EDIT - UPDATE

Basically there were a few corrections i had to make, so instead of going over each one.. Will just let you compare the changes.. Part of it is that the fade functions did not wait til they completed, the Delay command only applies to the jquery object and the append i reversed just for my visual sake.

Also the last part as you mentioned in the comments, was to swap appendTo with html.

Just as an extra bonus, a shuffle example:

JS Fiddle Showing With Shuffle Example: http://jsfiddle.net/ye3rjy2v/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...