js+jQuery实现网页打字机效果(带光标)js模拟光标打字
发布时间:2017-07-21, 19:23:08 分类:HTML | 编辑 off 网址 | 辅助
图集1/5
正文 5107字数 1,022,096阅读
在写网站的时候,有时候可能需要打字机动画去实现一些页面效果的显示,我在网上找了很久也没有很完整的,符合我要求的代码,索性就结合网上的大神们的代码段自己写了一个HTML
view plain copy
<div class="container"></div>
Run code
Cut to clipboard
CSS
view plain copy
.container{
float: left;
display: inline-block;
position: relative;
}
@keyframes blink-caret { 50% { background-color: transparent; } }
span{
animation:blink-caret 1s step-end infinite;
width: 3px;
height: 20px;
background-color: #000;
float: left;
position: absolute;
right: -10px;
}
Run code
Cut to clipboard
JS
view plain copy
var s = 'Welcome to LoVueAn';
var con = $('.container');
var index = 0;
var length = s.length;
var tId = null;
function start(){
con.text('');
con.append('<span></span>');
tId=setInterval(function(){
con.append(s.charAt(index));
if(index++ === length){
clearInterval(tId);
index = 0;
start()
}
},400);
}
start();
Run code
Cut to clipboard
效果图
这段代码采用了JS中的定时器,支持输入完之后归零再次动画,通过append添加了一个span标签模拟光标,css动画渲染闪烁效果,再通过绝对定位始终依附在父容器的右方以达到模拟输入效果的目的。注意在表头引入jquery!
网上搜索到的一般都是通过原生JS写出,但没有光标效果,纯CSS写出来的又对容器的宽要求很高,光标一直悬于最后方不利于实战开发,我认为这种方法相对较好
<!DOCTYPE html>
<html>
<head>
<title>李振球</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="icon" href="/favicon.ico">
<meta name="keywords" content="李振球">
<meta name="description" content="李振球">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no" />
<style>
*{padding:0px;margin:0px;}
html,body{height:100%;}
body{background:#000 url(86f740e5196bec328ee09cca4dd9c827.jpg);background-repeat: no-repeat;
background-size: cover;background-position: center;}
#main{width:100%;height:100%;background:url(5-120601093339.png);opacity: 0.45;}
#mainc{background: url(5-120601093354.gif);
display: inline-block;
color: #fff;
padding: 12px;
margin: 12px;
border-radius: 12px;}
</style>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<div style="display:none;"><!--缓存图片,背景图片闪白bug,修复刷新的时候背景闪一下才显示背景图片-->
<img src="86f740e5196bec328ee09cca4dd9c827.jpg">
<img src="5-120601093339.png">
<img src="5-120601093354.gif">
</div>
<div id="main">
<div id="mainc">
<p d="我的"></p>
<br />
<p d="生日:1990年2月13号"></p>
<p d="星座:水瓶男"></p>
<p d="大学:广西科技大学"></p>
<br />
<p d="工作:"></p>
<p d="2013:义乌 扬帆科技有限公司 美工"></p>
<p d="2014:绍兴 大海网络科技有限公司 技术"></p>
<p d="2015-至今:南宁 共振广告设计有限公司 技术、运维、网站运营"></p>
<br />
<p d="兴趣:互联网相关 各种先进IT技术 痴迷天文学物理学化学生物学等和科技沾边的"></p>
<p d="微信:iswtf_ 小程序可搜索 李振球"></p>
<p d="博客:blog.lizhenqiu.com"></p>
<p d="email:winwin@lizhenqiu.com"></p>
<p d="桂ICP备15007619号-3 阿里云提供云计算服务支持"></p>
<br />
<p d="2017.07.21"></p>
</div>
</div>
<script>
var sarr=new Array();
var tId;
$(document).ready(function(){
$('#mainc p').each(function(indexs){
var s = $(this).attr('d');
sarr[indexs]=s;
});
start(0);
});
function start(indexs){
var s=sarr[indexs];
if(!s) return false;
var sll=sarr.length;
var sl=s.length;
var con=$('#mainc').find('p:eq('+indexs+')');
var indexss = 0;
tId=setInterval(function(){
//if() return false;
//console.log(indexss);
if(!s || indexs>sll){
return false;
}
con.append(s.charAt(indexss));
indexss++;
if(indexss>sl){
clearInterval(tId);
indexs++;
start(indexs);
}
},100);
}
//console.log(sarr);
/*
var length = s.length;
var tId = null;
var that=$(this);
start(that,s,index,length,tId);
$(selector).index(element)
function start(con,s,indexs,length,tId){
var index = 0;
con.text('');
var tId=setInterval(function(){
con.append(s.charAt(index));
if(index++ === length){
clearInterval(tId);
}
},100);
}
*/
</script>
</body>
</html>
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
有过 5 条评论 »
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style>h1{ font: bold 200% Consolas, Monaco, monospace; border-right: .1em solid; width: 16.5em; /* fallback */ width: 20ch; /* # of chars */ margin: 2em 1em; white-space: nowrap; overflow: hidden; animation: typing 10s steps(20,end) 2 , blink .5s step-end infinite alternate; } @keyframes typing { from { width: 0; } } @keyframes blink { 50% { border-color: transparent; } } </style> </head> <body> <h1>This is hello world !</h1> </body> </html>
<div style="display:none;"><!--缓存图片,背景图片闪白bug,修复刷新的时候背景闪一下才显示背景图片--> <img src="86f740e5196bec328ee09cca4dd9c827.jpg"> <img src="5-120601093339.png"> <img src="5-120601093354.gif"> </div>
插件地址: https://github.com/mattboldt/typed.js/
<!doctype html> <html lang="zh"> <head> <title>神奇的前端输入模拟插件 -- typed.js</title> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta author="极客标签:www.gbtags.com" /> <meta name="Description" content="极客标签是一个基于web的在线极客编程知识分享&学习平台,能够帮助你快速高效地学习代码编程并方便的在线实时分享编程技巧和心得" /> <meta name="Keywords" content="极客,极客标签,轻视频,代码录播,在线调试,前端,前端社区,前端特效,素材,html5,javascript,css3,jquery,bootstrap,bootstrap3" /> <style> html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, menu, nav, section, time, mark, audio, video, details, summary { margin: 0; padding: 0; border: 0; font-size: 100%; vertical-align: baseline; background: transparent; } /* line 3, ../../_sass/404.scss */ #not-found, #not-found body { display: table; margin: 0; padding: 0; width: 100%; height: 100%; } /* line 11, ../../_sass/404.scss */ #not-found body { position: relative; background-color: #1d2b2a; background-image: url(404-stripe.png), url(404-noise.png); background-repeat: repeat-x, repeat; background-position: 0 0%; background-attachment: fixed; font-size: 21px; font-family: Inconsolata, "Lucida Console", Monaco, Courier, monospace; font-smooth: never; line-height: 2em; color: #d4f8e3; -webkit-font-smoothing: none; text-shadow: -2px 0 0px rgba(0, 0, 225, 0.4), -1px 0 3px rgba(103, 171, 236, 0.6), 1px 0 4px rgba(69, 112, 204, 0.5); -moz-animation: blink 0.1s steps(2, start) infinite, skip 7s linear infinite, flicker 0.1s steps(2, start) infinite; -webkit-animation: blink 0.1s steps(2, start) infinite, skip 7s linear infinite, flicker 0.1s steps(2, start) infinite; animation: blink 0.1s steps(2, start) infinite, skip 7s linear infinite, flicker 0.1s steps(2, start) infinite; } /* line 26, ../../_sass/404.scss */ #not-found body #holder { display: table-cell; vertical-align: bottom; max-width: 800px; margin: 0 auto; } /* line 32, ../../_sass/404.scss */ #not-found body #story1, #not-found body #story { padding: 10px 0 10px; max-width: 100%; white-space: pre; line-height: 1.25em; } /* line 38, ../../_sass/404.scss */ #not-found body #story1:after { visibility: visible; content: ''; background-color: #d4f8e3; display: inline-block; position: relative; width: 0.5em; height: 1em; top: 5px; margin-left: 0; -moz-box-shadow: -2px 0 0px rgba(0, 0, 225, 0.4), -1px 0 3px rgba(103, 171, 236, 0.6), 1px 0 4px rgba(69, 112, 204, 0.5); -webkit-box-shadow: -2px 0 0px rgba(0, 0, 225, 0.4), -1px 0 3px rgba(103, 171, 236, 0.6), 1px 0 4px rgba(69, 112, 204, 0.5); box-shadow: -2px 0 0px rgba(0, 0, 225, 0.4), -1px 0 3px rgba(103, 171, 236, 0.6), 1px 0 4px rgba(69, 112, 204, 0.5); -moz-animation: flicker 0.1s steps(2, start) infinite, ready 1s steps(2, start) 25s infinite; -webkit-animation: flicker 0.1s steps(2, start) infinite, ready 1s steps(2, start) 25s infinite; animation: flicker 0.1s steps(2, start) infinite, ready 1s steps(2, start) 25s infinite; } /* line 52, ../../_sass/404.scss */ #not-found body #kick { text-shadow: none; margin: 10px; } /* line 55, ../../_sass/404.scss */ #not-found body #kick a { background-color: #d4f8e3; color: #1d2b2a; } /* line 61, ../../_sass/404.scss */ #not-found body .typed-cursor { display: none; } @-moz-keyframes blink { to { background-color: #223332; } } @-webkit-keyframes blink { to { background-color: #223332; } } @keyframes blink { to { background-color: #223332; } } @-moz-keyframes skip { to { background-position: 0 100%; } } @-webkit-keyframes skip { to { background-position: 0 100%; } } @keyframes skip { to { background-position: 0 100%; } } @-moz-keyframes flicker { to { color: #bddeca; } } @-webkit-keyframes flicker { to { color: #bddeca; } } @keyframes flicker { to { color: #bddeca; } } @-moz-keyframes ready { to { visibility: hidden; } } @-webkit-keyframes ready { to { visibility: hidden; } } @keyframes ready { to { visibility: hidden; } } @media screen and (max-width: 400px) { /* line 84, ../../_sass/404.scss */ #not-found body { font-size: 18px; } } </style> </head> <body> <!-- HTML代码片段中请勿添加<body>标签 //--> <div id="holder"> <span id="story"></span> <span id="story1"></span> <div id="kick"></div> </div> <!-- 推荐开源CDN来选取需引用的外部JS //--> <script async="" src="http://cdn.gbtags.com/analytics.js/1.5.2/analytics.min.js"></script> <script type="text/javascript" src="http://cdn.gbtags.com/jquery/1.11.1/jquery.min.js"></script> <script> // The MIT License (MIT) // Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.com // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. ! function($) { "use strict"; var Typed = function(el, options) { // chosen element to manipulate text this.el = $(el); // options this.options = $.extend({}, $.fn.typed.defaults, options); // attribute to type into this.isInput = this.el.is('input'); this.attr = this.options.attr; // show cursor this.showCursor = this.isInput ? false : this.options.showCursor; // text content of element this.elContent = this.attr ? this.el.attr(this.attr) : this.el.text() // html or plain text this.contentType = this.options.contentType; // typing speed this.typeSpeed = this.options.typeSpeed; // add a delay before typing starts this.startDelay = this.options.startDelay; // backspacing speed this.backSpeed = this.options.backSpeed; // amount of time to wait before backspacing this.backDelay = this.options.backDelay; // input strings of text this.strings = this.options.strings; // character number position of current string this.strPos = 0; // current array position this.arrayPos = 0; // number to stop backspacing on. // default 0, can change depending on how many chars // you want to remove at the time this.stopNum = 0; // Looping logic this.loop = this.options.loop; this.loopCount = this.options.loopCount; this.curLoop = 0; // for stopping this.stop = false; // custom cursor this.cursorChar = this.options.cursorChar; // shuffle the strings this.shuffle = this.options.shuffle; // the order of strings this.sequence = []; // All systems go! this.build(); }; Typed.prototype = { constructor: Typed , init: function() { // begin the loop w/ first current string (global self.string) // current string will be passed as an argument each time after this var self = this; self.timeout = setTimeout(function() { for (var i=0;i<self.strings.length;++i) self.sequence[i]=i; // shuffle the array if true if(self.shuffle) self.sequence = self.shuffleArray(self.sequence); // Start typing self.typewrite(self.strings[self.sequence[self.arrayPos]], self.strPos); }, self.startDelay); } , build: function() { // Insert cursor if (this.showCursor === true) { this.cursor = $("<span class=\"typed-cursor\">" + this.cursorChar + "</span>"); this.el.after(this.cursor); } this.init(); } // pass current string state to each function, types 1 char per call , typewrite: function(curString, curStrPos) { // exit when stopped if (this.stop === true) { return; } // varying values for setTimeout during typing // can't be global since number changes each time loop is executed var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed; var self = this; // ------------- optional ------------- // // backpaces a certain string faster // ------------------------------------ // // if (self.arrayPos == 1){ // self.backDelay = 50; // } // else{ self.backDelay = 500; } // contain typing function in a timeout humanize'd delay self.timeout = setTimeout(function() { // check for an escape character before a pause value // format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^ // single ^ are removed from string var charPause = 0; var substr = curString.substr(curStrPos); if (substr.charAt(0) === '^') { var skip = 1; // skip atleast 1 if (/^\^\d+/.test(substr)) { substr = /\d+/.exec(substr)[0]; skip += substr.length; charPause = parseInt(substr); } // strip out the escape character and pause value so they're not printed curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip); } if (self.contentType === 'html') { // skip over html tags while typing var curChar = curString.substr(curStrPos).charAt(0) if (curChar === '<' || curChar === '&') { var tag = ''; var endTag = ''; if (curChar === '<') { endTag = '>' } else { endTag = ';' } while (curString.substr(curStrPos).charAt(0) !== endTag) { tag += curString.substr(curStrPos).charAt(0); curStrPos++; } curStrPos++; tag += endTag; } } // timeout for any pause after a character self.timeout = setTimeout(function() { if (curStrPos === curString.length) { // fires callback function self.options.onStringTyped(self.arrayPos); // is this the final string if (self.arrayPos === self.strings.length - 1) { // animation that occurs on the last typed string self.options.callback(); self.curLoop++; // quit if we wont loop back if (self.loop === false || self.curLoop === self.loopCount) return; } self.timeout = setTimeout(function() { self.backspace(curString, curStrPos); }, self.backDelay); } else { /* call before functions if applicable */ if (curStrPos === 0) self.options.preStringTyped(self.arrayPos); // start typing each new char into existing string // curString: arg, self.el.html: original text inside element var nextString = curString.substr(0, curStrPos + 1); if (self.attr) { self.el.attr(self.attr, nextString); } else { if (self.isInput) { self.el.val(nextString); } else if (self.contentType === 'html') { self.el.html(nextString); } else { self.el.text(nextString); } } // add characters one by one curStrPos++; // loop the function self.typewrite(curString, curStrPos); } // end of character pause }, charPause); // humanized value for typing }, humanize); } , backspace: function(curString, curStrPos) { // exit when stopped if (this.stop === true) { return; } // varying values for setTimeout during typing // can't be global since number changes each time loop is executed var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed; var self = this; self.timeout = setTimeout(function() { // ----- this part is optional ----- // // check string array position // on the first string, only delete one word // the stopNum actually represents the amount of chars to // keep in the current string. In my case it's 14. // if (self.arrayPos == 1){ // self.stopNum = 14; // } //every other time, delete the whole typed string // else{ // self.stopNum = 0; // } if (self.contentType === 'html') { // skip over html tags while backspacing if (curString.substr(curStrPos).charAt(0) === '>') { var tag = ''; while (curString.substr(curStrPos).charAt(0) !== '<') { tag -= curString.substr(curStrPos).charAt(0); curStrPos--; } curStrPos--; tag += '<'; } } // ----- continue important stuff ----- // // replace text with base text + typed characters var nextString = curString.substr(0, curStrPos); if (self.attr) { self.el.attr(self.attr, nextString); } else { if (self.isInput) { self.el.val(nextString); } else if (self.contentType === 'html') { self.el.html(nextString); } else { self.el.text(nextString); } } // if the number (id of character in current string) is // less than the stop number, keep going if (curStrPos > self.stopNum) { // subtract characters one by one curStrPos--; // loop the function self.backspace(curString, curStrPos); } // if the stop number has been reached, increase // array position to next string else if (curStrPos <= self.stopNum) { self.arrayPos++; if (self.arrayPos === self.strings.length) { self.arrayPos = 0; // Shuffle sequence again if(self.shuffle) self.sequence = self.shuffleArray(self.sequence); self.init(); } else self.typewrite(self.strings[self.sequence[self.arrayPos]], curStrPos); } // humanized value for typing }, humanize); } /** * Shuffles the numbers in the given array. * @param {Array} array * @returns {Array} */ ,shuffleArray: function(array) { var tmp, current, top = array.length; if(top) while(--top) { current = Math.floor(Math.random() * (top + 1)); tmp = array[current]; array[current] = array[top]; array[top] = tmp; } return array; } // Start & Stop currently not working // , stop: function() { // var self = this; // self.stop = true; // clearInterval(self.timeout); // } // , start: function() { // var self = this; // if(self.stop === false) // return; // this.stop = false; // this.init(); // } // Reset and rebuild the element , reset: function() { var self = this; clearInterval(self.timeout); var id = this.el.attr('id'); this.el.after('<span id="' + id + '"/>') this.el.remove(); if (typeof this.cursor !== 'undefined') { this.cursor.remove(); } // Send the callback self.options.resetCallback(); } }; $.fn.typed = function(option) { return this.each(function() { var $this = $(this), data = $this.data('typed'), options = typeof option == 'object' && option; if (!data) $this.data('typed', (data = new Typed(this, options))); if (typeof option == 'string') data[option](); }); }; $.fn.typed.defaults = { strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"], // typing speed typeSpeed: 0, // time before typing starts startDelay: 0, // backspacing speed backSpeed: 0, // shuffle the strings shuffle: false, // time before backspacing backDelay: 500, // loop loop: false, // false = infinite loopCount: false, // show cursor showCursor: true, // character for cursor cursorChar: "|", // attribute to type (null == text) attr: null, // either html or text contentType: 'html', // call when done callback function callback: function() {}, // starting callback function before each string preStringTyped: function() {}, //callback for every typed string onStringTyped: function() {}, // callback for reset resetCallback: function() {} }; }(window.jQuery); $("html").attr("id", "not-found"); $(function(){ var weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]; var dayOfWeekIndex = (new Date()).getDay(); var dayOfWeek = weekdays[dayOfWeekIndex]; var dayOfWeekPastIndex = Math.floor(weekdays.length * Math.random()); var dayOfWeekPast; var hourOfDay = new Date().getHours(); var timeOfDay; // choose day of week other than current one if (dayOfWeekPastIndex == dayOfWeekIndex) { dayOfWeekPast = weekdays[(dayOfWeekPastIndex + 1) % weekdays.length]; } else { dayOfWeekPast = weekdays[dayOfWeekPastIndex]; } // assign time of day to the hour if ((hourOfDay >= 4) && (hourOfDay <= 11)) { timeOfDay = "早上"; } else if ((hourOfDay >= 12) && (hourOfDay <= 16)) { timeOfDay = "下午"; } else { timeOfDay = "晚上"; } // make conversation $('#story').typed({ strings: ["大家好,我们" + dayOfWeekPast + "是不是见过面?^2000\n在这个" + dayOfWeek + "的" + timeOfDay + "...^2000\n我要给大家介绍一下我.^2000\n我就是一个程序员.^2000\n平时也没什么爱好.^2000\n我有一个理想,那就是.^1000.^1000.^1000\n"], typeSpeed: 50, backDelay: 800, loop: false, loopCount: false, callback: function(){ $('#story1').typed({ strings: ["金钱与美女,^2000额...", "事业和爱情.^2000\n我爱写程序.^2000\n我爱做很Cool的东西.^2000\n谢谢..."], typeSpeed: 50, backDelay: 500, loop: false, loopCount: false }); } }); }); </script> <script type="text/javascript"> var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://"); document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fac45a0f68a119fbe4d1c4c3ac3044dbd' type='text/javascript'%3E%3C/script%3E")); </script> </body> </html>
js星期几上下午几点时间
<script type="text/javascript" src="https://lizhenqiu.com/templates/default/jquery.min.js"></script> <script>$(function(){ var weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]; var dayOfWeekIndex = (new Date()).getDay(); var dayOfWeek = weekdays[dayOfWeekIndex]; var dayOfWeekPastIndex = Math.floor(weekdays.length * Math.random()); var dayOfWeekPast; var hourOfDay = new Date().getHours(); var timeOfDay; // choose day of week other than current one if (dayOfWeekPastIndex == dayOfWeekIndex) { dayOfWeekPast = weekdays[(dayOfWeekPastIndex + 1) % weekdays.length]; } else { dayOfWeekPast = weekdays[dayOfWeekPastIndex]; } // assign time of day to the hour if ((hourOfDay >= 4) && (hourOfDay <= 11)) { timeOfDay = "早上"; } else if ((hourOfDay >= 12) && (hourOfDay <= 16)) { timeOfDay = "下午"; } else { timeOfDay = "晚上"; } // make conversation alert("大家好,我们" + dayOfWeekPast + "是不是见过面?^2000\n在这个" + dayOfWeek + "的" + timeOfDay); }); </script>
https://dimtown.com/
搜番
https://sofan.icu/
solji.kim