以下是 jQuery打字机插件typeit.js特效代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700' rel='stylesheet' type='text/css'>-->
<link rel="stylesheet" href="src/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="dist/typeit.min.css">
<link rel="stylesheet" type="text/css" href="src/style.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery打字机插件typeit.js</title>
</head>
<body>
<a name="top"></a>
<header>
<h1 class="main-header">TypeIt</h1>
<hr>
<span class="typeit-box"></span>
</header>
<div class="container">
<section>
<form id="TIInput">
<h2 class="ti-header">Try it!</h2>
<span class="info">Tweak the settings (optional), enter at least one string, and watch it go!</span>
<div class="options-holder">
<div class="ti-option-box">
<label>Type Speed</labeL>
<input class="ti-option" type="number" id="iTypeSpeed" placeholder="typeSpeed">
</div>
<div class="ti-option-box">
<label>Life-Like</labeL>
<select class="ti-option" id="iLifeLike">
<option value="true" selected>True</option>
<option value="false">False</option>
</select>
</div>
<div class="ti-option-box">
<label>Show Cursor</labeL>
<select class="ti-option" id="iShowCursor">
<option value="true" selected>True</option>
<option value="false">False</option>
</select>
</div>
<div class="ti-option-box">
<label>Break Lines</labeL>
<select class="ti-option" id="iBreakLines">
<option value="true" selected>True</option>
<option value="false">False</option>
</select>
</div>
<div class="ti-option-box">
<label>Break Wait</labeL>
<input class="ti-option" type="number" id="iBreakWait" placeholder="breakWait">
</div>
<div class="ti-option-box">
<label>Delay Start</labeL>
<input class="ti-option" type="number" id="iDelayStart" placeholder="breakStart">
</div>
<a href="#options" class="settings-link">Wait, what do these settings actually do?</a>
<textarea rows="3" id="stringTI" placeholder="Enter one or multiple strings per line here."></textarea>
</div>
<input type="submit" id="TISubmit" value="Type it!">
</form>
<div class="ti-output-box">
<div id="TIOutput">
<span class="temp-text">output box</span>
</div>
</div>
<a id="scrollTo"></a>
</section>
<hr class="section-divider">
<section>
<h2>Start Typing on Your Site!</h2>
<div class="left">
<h3>To get it going, just initialize with a string:</h3>
<button class="btn-example1">Rerun</button>
</div>
<div class="right">
<div class="code-block code-input">
<small>Code</small>
<p class="example1"></p>
<br>
<br>
$('.example1').typeIt({<br>
whatToType: "You've just initialized this bad boy.",<br>
typeSpeed: 100<br>
});
</div>
<div class="code-block code-output">
<small>Output</small>
<p class="example1"></p>
</div>
</div>
</section>
<hr class="section-divider">
<section>
<div class="left">
<h3>Or, do it with data-typeit-* attributes:</h3>
<button class="btn-example2">Rerun</button>
</div>
<div class="right">
<div class="code-block code-input">
<small>Code</small>
<p class="example2" data-typeit-whattotype="This was defined with a data-typeit-* attribute." data-typeit-typeSpeed="100"></p>
<br>
<br>
$('.example2').typeIt();
</div>
<div class="code-block code-output">
<small>Output</small>
<p class="example2" data-typeit-whattotype="This was defined with a data-typeit-* attribute." data-typeit-typeSpeed="100"></p>
</div>
</div>
</section>
<hr class="section-divider">
<section>
<div class="left">
<h3>You can even use multiple strings that stack on each other:</h3>
<button class="btn-example3">Rerun</button>
</div>
<div class="right">
<div class="code-block code-input">
<small>Code</small>
<p class="example3"></p>
<br>
<br>
$('.example3').typeIt({<br>
whatToType: ["This is a string!", "And here's another one."],<br>
typeSpeed: 100<br>
});
</div>
<div class="code-block code-output">
<small>Output</small>
<p class="example3"></p>
</div>
</div>
</section>
<hr class="section-divider">
<section>
<div class="left">
<h3>Or use multiple strings that delete & replace each other:</h3>
<button class="btn-example4">Rerun</button>
</div>
<div class="right">
<div class="code-block code-input">
<small>Code</small>
<p class="example4"></p>
<br>
<br>
$('.example4').typeIt({<br>
whatToType: ["This is a great string.", "But here is a better one."],<br>
typeSpeed: 100,<br>
breakLines: false<br>
});
</div>
<div class="code-block code-output">
<small>Output</small>
<p class="example4"></p>
</div>
</div>
</section>
<hr class="section-divider">
<section>
<a name="options"></a>
<h3>There are plenty of settings to tweak how you desire:</h3>
<br>
<table>
<tr>
<th>Option</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td>whatToType</td>
<td>The string or strings you'd like to type.</td>
<td>"You probably want to replace this string."</td>
</tr>
<tr>
<td>typeSpeed</td>
<td>The speed (milliseconds) at which you want to type.</td>
<td>250</td>
</tr>
<tr>
<td>lifeLike</td>
<td>Choose whether the plugin types at a constant pace or irregular, lifelike pace.</td>
<td>true</td>
</tr>
<tr>
<td>showCursor</td>
<td>Choose whether you want the blinking cursor to appear when typing.</td>
<td>true</td>
</tr>
<tr>
<td>breakLines</td>
<td>Choose whether you want multiple strings to be printed on top of each other (breakLines = true), or if you want each string to be deleted and replaced by the next one (breakLines = false).</td>
<td>true</td>
</tr>
<tr>
<td>breakWait</td>
<td>The amount of time between typing multiple strings.</td>
<td>500</td>
</tr>
<tr>
<td>delayStart</td>
<td>The amount of time before the plugin begins typing after initializing.</td>
<td>250</td>
</tr>
</table>
</section>
<br>
<a href="#top">Back to Top</a>
</div>
<script src="src/jquery-2.1.4.min.js"></script>
<script src="dist/typeit.min.js"></script>
<script src="src/scripts.min.js"></script>
</body>
</html>
JS代码(scripts.js):
$('.typeit-box').typeIt({
whatToType:['A jQuery plugin that types stuff for you.'],typeSpeed:100}
);
$('.example1').typeIt({
whatToType:"You've just initialized this bad boy.",typeSpeed:100}
);
$('section').on('click','.btn-example1',function(){
$('.example1').data().typeit.stopTyping();
$('.example1').html('');
$('.example1').typeIt({
whatToType:"You've just initialized this bad boy.",typeSpeed:100}
);
}
);
$('.example2').typeIt();
$('section').on('click','.btn-example2',function(){
$('.example2').data().typeit.stopTyping();
$('.example2').html('');
$('.example2').typeIt();
}
);
$('.example3').typeIt({
whatToType:["This is a string!","And here's another one."],typeSpeed:100}
);
$('section').on('click','.btn-example3',function(){
$('.example3').data().typeit.stopTyping();
$('.example3').html('');
$('.example3').typeIt({
whatToType:["This is a string!","And here's another one."],typeSpeed:100}
);
}
);
$('.example4').typeIt({
whatToType:["This is a great string.","But here is a better one."],typeSpeed:100,breakLines:false}
);
$('section').on('click','.btn-example4',function(){
$('.example4').data().typeit.stopTyping();
$('.example4').html('');
$('.example4').typeIt({
whatToType:["This is a great string.","But here is a better one."],typeSpeed:100,breakLines:false}
);
}
);
(function(){
$('#iTypeSpeed').val('250');
$('#iBreakWait').val('500');
$('#iDelayStart').val('250');
$('#TIInput').on('click','#TISubmit',function(e){
e.preventDefault();
// if there's another process going on,stop it and wipe the output box if($.hasData($(this))){
$(this).data().typeit.stopTyping();
}
$('#TIOutput').html('');
// get variables figured out var whatToType;
var cleanedWhatToType = [];
if($('#stringTI').val() === ''){
cleanedWhatToType = 'You didn\'t enter a string!';
}
else{
whatToType = $('#stringTI').val().split('\n');
// remove empty array item for (var i = 0;
i < whatToType.length;
i++){
if (whatToType[i] !== undefined && whatToType[i] !== null && whatToType[i] !== ""){
cleanedWhatToType.push(whatToType[i]);
}
}
}
var newHeight = ($('#stringTI').val()) ? (cleanedWhatToType.length * 38) + 40:75;
var typeSpeed = $('#iTypeSpeed').val();
var lifeLike = $('#iLifeLike').val();
if(lifeLike === 'true'){
lifeLike = true;
}
else{
lifeLike = false;
}
var showCursor = $('#iShowCursor').val();
if(showCursor === 'true'){
showCursor = true;
}
else{
showCursor = false;
}
var breakLines = $('#iBreakLines').val();
if(breakLines === 'true'){
breakLines = true;
}
else{
breakLines = false;
}
var breakWait = $('#iBreakWait').val();
var breakStart = $('#iBreakStart').val();
var delayStart = $('#iDelayStart').val();
// hide the temp text $('.temp-text').animate({
opacity:0}
);
// expand the container $('.ti-output-box').animate({
height:newHeight}
,function(){
$('html,body').animate({
scrollTop:$(".ti-output-box").offset().top - 200}
,800);
setTimeout(function(){
$('#TIOutput').typeIt({
whatToType:cleanedWhatToType,typeSpeed:typeSpeed,lifeLike:lifeLike,showCursor:showCursor,breakLines:breakLines,breakWait:breakWait,breakStart:breakStart,delayStart:delayStart}
);
}
,800);
}
);
}
);
}
)();
$(function(){
$('a[href*=#]:not([href=#])').click(function(){
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname){
var target = $(this.hash);
target = target.length ? target:$('[name=' + this.hash.slice(1) +']');
if (target.length){
$('html,body').animate({
scrollTop:target.offset().top}
,1000);
return false;
}
}
}
);
}
);
JS代码(typeit.js):
/** * jQuery TypeIt * @author Alex MacArthur (http://macarthur.me) * @version 1.2.0 * @copyright 2015 Alex MacArthur * @description Types out a given string or strings. */
(function($){
// the actual jQuery function $.fn.typeIt = function(options,callback){
// now call a callback function return this.each(function(){
$(this).data("typeit",new $.fn.typeIt.typeItClass($(this),options,callback));
}
);
}
;
// create the class $.fn.typeIt.typeItClass = function(theElement,options,callback){
// plugin default settings this.defaults ={
whatToType:'This is the default string. Please replace this string with your own.',typeSpeed:200,lifeLike:false,showCursor:true,breakLines:true,breakWait:500,delayStart:250}
;
this.dataDefaults ={
whatToType:theElement.data('typeitWhattotype'),typeSpeed:theElement.data('typeitSpeed'),lifeLike:theElement.data('typeitLifelike'),showCursor:theElement.data('typeitShowcursor'),breakLines:theElement.data('typeitBreaklines'),breakWait:theElement.data('typeitBreakWait'),delayStart:theElement.data('typeitDelayStart')}
;
// the element that holds the text this.theElement = theElement;
// callback function that executes after strings have been printed this.callback = callback;
// the settings for the plugin instance this.settings = $.extend({
}
,this.defaults,options,this.dataDefaults);
// the number of types a character has been typed for each pass over a string this.typeCount = 0;
// the character number of a string that's currently being deleted this.deleteCount = 0;
// the string number that's currently being typed or deleted this.stringCount = 0;
this.stringPlaceCount = 0;
// the length of the current string being handled this.phraseLength = 0;
this.cursor = '';
this.deleteTimeout = null;
this.typeTimeout = null;
this.shortenedText = null;
if(typeof this.callback != 'function'){
console.log('Your callback is not a valid function. Please format your callback as "function(){
...}
" when it is defined.');
}
this.init(theElement);
}
;
// create a new prototype var _proto = $.fn.typeIt.typeItClass.prototype;
// initialize the plugin _proto.init = function(theElement){
this.stringArray = this.settings.whatToType;
// check if the value is an array or just a string if(Object.prototype.toString.call(this.stringArray) !== '[object Array]'){
// since it's not already an array,turn it into one,since later functionality depends on it being one this.stringArray = '["' + this.stringArray + '"]';
this.stringArray = JSON.parse(this.stringArray);
}
this.mergedStrings = this.stringArray.join('');
this.stringLengths ={
}
;
this.phraseLength = this.stringLengths[this.stringCount];
// get the string lengths and save to array,set up ti-containers for each string for(j=0;
j < this.stringArray.length;
j++){
this.stringLengths[j] = this.stringArray[j].length;
// set up the number of ti-containers we'll need to hold the strings theElement.append('<span class="ti-container"><span class="ti-text-container ti-cursor"></span></span>');
}
// add .active-container to the first .ti-text-container so the cursor starts blinking before a string is printed theElement.find('.ti-container:first-child').find('.ti-text-container').addClass('active-container');
// if breakLines is false,then we for sure only need ONE ti-container even if there multiple strings,so make sure of that if(this.settings.breakLines === false){
theElement.find('.ti-container').remove();
theElement.append('<span class="ti-container"><span class="ti-text-container ti-cursor"></span></span>');
}
// if showCursor is false,then remove the ti-cursor class if(this.settings.showCursor === false){
$(this.theElement).find('.ti-text-container').removeClass('ti-cursor');
}
// start to type the string(s) setTimeout(function(){
this.typeLoop();
}
.bind(this),this.settings.delayStart);
}
;
_proto.typeLoop = function(){
// set the length of the current phrase being typed this.phraseLength = this.stringLengths[this.stringCount];
// make it human-like if specified in the settings if(this.settings.lifeLike === true){
this.delayTime = this.settings.typeSpeed*Math.random();
}
else{
this.delayTime = this.settings.typeSpeed;
}
this.typeTimeout = setTimeout(function (){
// append the string of letters to the respective .ti-text-container var characterToAppend = this.mergedStrings[this.typeCount+this.stringPlaceCount];
// if breakLines is set to true,add the 'active-container' class to the next .ti-text-container in the list. if(this.settings.breakLines === true){
$(this.theElement).find('.ti-text-container:eq('+ this.stringCount +')').addClass('active-container').append(characterToAppend);
}
else{
$(this.theElement).find('.ti-text-container').addClass('active-container').append(characterToAppend);
}
this.typeCount++;
// if there are still characters to be typed,call the same function again if (this.typeCount < this.phraseLength){
this.typeLoop(this.stringLengths[this.stringCount]);
// if there are no more characters to print and there is more than one string to be typed,delete the string just printed}
else if(this.stringArray.length > 1){
// update the this.stringPlaceCount so that we're appending starting at the correct spot in the merged string this.stringPlaceCount = this.stringPlaceCount + this.phraseLength;
// reset this.typeCount in case this function needs to be reused this.typeCount = 0;
// if the stringCount is the same as the number of strings we started with,we're done,so call the callback function if(this.stringCount+1 === this.stringArray.length){
this.callback();
// if we're not on the last string,then move on to to delete,unless the user wants to break lines}
else if((this.stringCount+1 < this.stringArray.length) && this.settings.breakLines === false){
setTimeout(function(){
this.deleteLoop();
}
.bind(this),this.settings.breakWait);
// if breakLines is true and we still have strings left to type,break it and continue}
else if (this.stringCount+1 < this.stringArray.length && this.settings.breakLines === true){
this.stringCount++;
setTimeout(function(){
// remove any 'active-container' classes fromt the elements $(this.theElement).find('.ti-text-container').removeClass('active-container');
// give 'active-container' class to next container,so the cursor can start blinking $(this.theElement).find('.ti-text-container:eq('+ this.stringCount +')').addClass('active-container');
// after another slight delay,continue typing the next string setTimeout(function(){
this.typeLoop();
}
.bind(this),this.settings.breakWait);
}
.bind(this),this.settings.breakWait);
}
// since there are no more strings to be typed,we're done and can call the callback function}
else{
this.callback();
}
}
.bind(this),this.delayTime);
}
;
_proto.deleteLoop = function(){
this.deleteTimeout = setTimeout(function (){
// get the string from the element and cut it by one character at the end shortenedText = $(this.theElement).find('.ti-text-container').text().substring(0,$(this.theElement).find('.ti-text-container').text().length - 1);
// then,put that shortened text into the element so it looks like it's being deleted $(this.theElement).find('.ti-text-container').text(shortenedText);
this.deleteCount++;
// if there are still characters in the string,run the function again if (this.deleteCount < this.phraseLength){
this.deleteLoop();
// if there are still strings in the array,go back to typing.}
else if(this.stringArray[this.stringCount+1] !== undefined){
this.deleteCount = 0;
this.stringCount++;
this.typeLoop();
}
// make backspacing much quicker by dividing delayTime (arbitrarily) by three}
.bind(this),this.delayTime/3);
}
;
// stop the plugin from typing or deleting stuff whenever it's called _proto.stopTyping = function(){
clearTimeout(this.typeTimeout);
clearTimeout(this.deleteTimeout);
}
;
}
(jQuery));