css实现
@keyframes typing { from { width: 0; } }
@keyframes blink-caret { 50% { border-color: transparent; } }
h1 {
font: bold 200% Consolas, Monaco, monospace;
border-right: .1em solid;
width: 16.5em; /* fallback */
width: 30ch; /* # of chars */
margin: 2em 1em;
white-space: nowrap;
overflow: hidden;
animation: typing 20s steps(30, end), /* # of steps = # of chars */
blink-caret .5s step-end infinite alternate;
}
js实现
html:
<span id = "first-default" > This is <p id = "first-words" > </p></span>
js:
var types = ["abcd.", "efgh.", "ijkl."],
words = document.getElementById("first-words"),
stopType = false; //用于停止自动打字的,false表示继续打,
index = 0,
tempWords = "",
isNext = false,
time = 200;
var startType = setInterval(function () {
if (stopType) {
//如果需要停止打字
clearInterval(startType);
}
if (tempWords.length === 0) {
//如果删完了,就开始
if (isNext) { //减少
index++; //types数组元素下标
index = index % 3; //types数组长度为3
isNext = false;
}
tempWords = types[index].substring(0, tempWords.length + 1); //第一个字
} else if (tempWords.length === types[index].length && isNext === false) {
//如果已经到头了,就要删去
// tempWords = tempWords.substring(0,tempWords.length-1);
isNext = true;
time = 5000;
} else {
//如果既没删完也没显示完
if (isNext) {
//如果是在减少
tempWords = tempWords.substring(0, tempWords.length - 1);
time = 150;
} else {
//如果在增多
time = 200;
tempWords = types[index].substring(0, tempWords.length + 1);
}
}
words.innerHTML = ' ' + tempWords;
}, time);
hash控制页面
html:
<article className = "container" >
<section id = "page1" className = "page cur" > 第一页 </section>
<section id = "page2" className = "page" > 第二页 </section>
<section id = "page3" className = "page" > 第三页 </section>
</article>
<nav id = "nav" className = "bottom-nav" >
<ul>
<li> 第一页 </li>
<li> 第二页 </li>
<li> 第三页 </li>
</ul>
</nav>
js:
var nav = document.getElementById('nav');
var navLi = nav.getElementsByTagName('li');
for (var i = 0, len = navLi.length; i < len; i++) {
(function (i) {
navLi[i].onclick = function () { //点击nav中的li,改变hash值
window.location.hash = 'page' + (i + 1);
}
})(i);
}
window.location.hash = 'page1'; //每次页面重新加载时都回到page1
window.onhashchange = function (e) {
//当hash变化时,执行hashchange事件,该事件具有oldURL和newURL两个事件属性,分别代表前一个URL和目前的URL
var oldHash = e.oldURL.split('#')[1]; //取得前一个hash
var newHash = e.newURL.split('#')[1]; //取得当前hash
var oldPage = document.getElementById(oldHash);
var newPage = document.getElementById(newHash);
oldPage.classList.remove('cur'); //隐藏前一个page
newPage.classList.add('cur'); //显示当前page
};