开发者

Javascript loop when setinterval is done

开发者 https://www.devze.com 2023-02-18 18:03 出处:网络
Please help me to loop this script when done the interval, when the class=\"cur\" goes to last p span i would like to loop it again. I\'m practicing a javascript code and this is what i made.

Please help me to loop this script when done the interval, when the class="cur" goes to last p span i would like to loop it again. I'm practicing a javascript code and this is what i made.

<script type="te开发者_开发技巧xt/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<p style="font-size: 50px">This is a test</p>
<script>
function blink() {
   $('.cur').next().css('color', '#333').addClass('cur');
   $('.cur:first').css('color', '#ccc').removeClass('cur');
}
var str = $('p').text();
var count = str.length - 1;
var splt = str.split("");
var newstr = "";
for(i=0;i<=count;i++) {
   newstr += splt[i].replace(splt[i],"<span style='color: #CCC;'>"+splt[i]+"</span>");
}
$('p').empty().append(newstr);
$('p span:first').addClass('cur').css('color','#333');
setInterval('blink()', 100);
</script>


setTimeout instead of setInterval?


You need to check if the next .cur still exists.. when it doesn't exist (length 0 of the collection) start over:

function blink() {
   if ($('.cur').next().length == 0) {
       $('p span:first').addClass('cur').css('color','#333');
       $('p span:last').removeClass('cur').css('color','#ccc');
       return;
   }
   $('.cur').next().css('color', '#333').addClass('cur');
   $('.cur:first').css('color', '#ccc').removeClass('cur');
}

Live test case: http://jsfiddle.net/yahavbr/QKYHt/


If $('.cur').next() is an empty array you need to go back to the first span again:

function blink() {
    var cur = $('.cur');
    var next = $(cur).next();
    if (next.length == 0) {
        next = $('p span:first');
    }

   $(next).addClass('cur');
   $(cur).removeClass('cur');
}

Working demo at http://jsfiddle.net/cqkPV/3/

Note that this doesn't need any pre-setup - the first time it's called it'll correctly highlight the first element. Calling $(...).method() on an empty list is a NoOp in jQuery.

NB: I've removed the explicit colour from the spans and the .css calls and moved the highlight colors into a CSS file.

0

精彩评论

暂无评论...
验证码 换一张
取 消