如何使用jQuery/javascript创建文本类型writer效果?
我试着用谷歌搜索,找到了jtypewriter,但是在上给出的Demo页面jQuery Plugin jtypewriter
不工作/打开。
链接:http://archive.plugins.jquery.com/project/jTypeWriter
project's home page
也不工作
问题:
- 如何使用jQuery或java脚本创建文本类型写入器效果? 是否有办法通过任何其他技巧获得相同的效果?
我想你说的text type writer effect
是指Microsoft PowerPoint演示幻灯片动画中的那个:)
。随机彩色文本从左到右显示,有一点延迟。
您可以创建自己的。看看我做的这个非常简单(和丑陋)的演示:
var data="this is the data to be shown in effect";
var index=0;
var cursor="<span id='cursor'>_</span>";
$('.content').append(cursor);
function test(){
//Clear the interval once entire characters are processed
if(index>=data.length-1){
clearInterval(T);
}
//Generate random color
var hue = 'rgb('
+ (Math.floor(Math.random() * 256)) + ','
+ (Math.floor(Math.random() * 256)) + ','
+ (Math.floor(Math.random() * 256)) + ')';
//wrap each of the characters in a span tag with the currently generated
//random style color.
_span = '<span style="color:'+hue+'">'+data[index]+'</span>';
//and append the span just before the cursor
$('#cursor').before(_span);
index++;
}
//call the function repeatedly, till all the characters are processed, hence
//setInterval(code,duration)
var T=setInterval("test()",200);
参见FIDDLE
如果你想增加动画效果,只需减少setInterval中的Interval,反之亦然。此外,您还可以通过原型设计使其更优雅。
它应该给你一个想法。
重新启动。只需这样做,而不是清除间隔
if(index>=data.length-1){
$('span').not('#cursor').remove();
index=0;
}
小提琴
这是如何使用jQuery创建文本打字机效果的示例
演示:http://jsbin.com/araget/5/
插件:
(function ($) {
// writes the string
//
// @param jQuery $target
// @param String str
// @param Numeric cursor
// @param Numeric delay
// @param Function cb
// @return void
function typeString($target, str, cursor, delay, cb) {
$target.html(function (_, html) {
return html + str[cursor];
});
if (cursor < str.length - 1) {
setTimeout(function () {
typeString($target, str, cursor + 1, delay, cb);
}, delay);
}
else {
cb();
}
}
// clears the string
//
// @param jQuery $target
// @param Numeric delay
// @param Function cb
// @return void
function deleteString($target, delay, cb) {
var length;
$target.html(function (_, html) {
length = html.length;
return html.substr(0, length - 1);
});
if (length > 1) {
setTimeout(function () {
deleteString($target, delay, cb);
}, delay);
}
else {
cb();
}
}
// jQuery hook
$.fn.extend({
teletype: function (opts) {
var settings = $.extend({}, $.teletype.defaults, opts);
return $(this).each(function () {
(function loop($tar, idx) {
// type
typeString($tar, settings.text[idx], 0, settings.delay, function () {
// delete
setTimeout(function () {
deleteString($tar, settings.delay, function () {
loop($tar, (idx + 1) % settings.text.length);
});
}, settings.pause);
});
}($(this), 0));
});
}
});
// plugin defaults
$.extend({
teletype: {
defaults: {
delay: 100,
pause: 5000,
text: []
}
}
});
}(jQuery));