I'm new to JavaScript and I have found this cool jQuery text departure board effect http://jsfiddle.net/aino/9yyVd/
JavaScript
$.fn.ticker = function( options ) {
options = $.extend({
uppercase: true,
extra: ',.:+=/()',
speed: 30
}, options);
var alph = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
if ( !options.uppercase ) {
开发者_Python百科 alph = alph + alph.toLowerCase();
}
alph = '01234567890'+alph + options.extra + ' ';
return this.each(function() {
var k = 1,
elems = $(this).children(),
arr = alph.split(''),
len = 0,
fill = function( a ) {
while( a.length < len ) {
a.push(' ');
}
return a;
},
texts = $.map( elems, function( elem ) {
var text = $(elem).text();
len = Math.max(len, text.length);
return options.uppercase ? text.toUpperCase() : text;
}),
target = $('<div>'),
render = function(print) {
target.data('prev', print.join(''));
fill(print);
print = $.map(print, function(p) {
return p == ' ' ? ' ' : p;
});
return target.html('<span>' + print.join('</span><span>') + '</span>');
},
attr = {}
$.each(this.attributes, function(i, item) {
target.attr( item.name, item.value );
});
$(this).replaceWith( render( texts[0].split('') ) );
target.click(function(e) {
var next = fill(texts[k].split('')),
prev = fill(target.data('prev').split('')),
print = prev;
$.each(next, function(i) {
if (next[i] == prev[i]) {
return;
}
var index = alph.indexOf( prev[i] ),
j = 0,
tid = window.setInterval(function() {
if ( next[i] != arr[index] ) {
index = index == alph.length-1 ? 0 : index + 1;
} else {
window.clearInterval(tid);
}
print[i] = alph[index];
render(print);
}, options.speed)
});
k = k == texts.length-1 ? 0 : k + 1;
});
});
};
$('#text').ticker();
HTML
<ul id="text">
<li>4032 London</li>
<li>5901 Paris</li>
<li>9954 Cologne</li>
<li>4204 St. Petersburg</li>
</ul>
<p>↑ Click</p>
CSS
#text{cursor:pointer;overflow:hidden;font:40px/1 monospace;}
#text span{display:block;float:left;background:#444;
color:#fff;margin-right:1px;}
I notice the script changes to the next part of the array after the div is clicked, which has something to do with target.click
I guess.
How can I change this to change onload
?
Sure, just change target.click
to $(document).ready
.
I've edited the example to demonstrate.
If you remove the target.click(function(e) {
this will work "onload" - http://jsfiddle.net/9yyVd/138/
But, if you want to keep the click() trigger, you can trigger the click once it's loaded. You can do that with $('#text').trigger('click')
- http://jsfiddle.net/9yyVd/139/
Just use .ready() instead .click() ;)
http://api.jquery.com/ready/
精彩评论