今天看到一个有意思的动态的99乘法表,于是动手也写了一个,要求如下:
用html,css,原生js实现如图的效果,先正向输出,然后逆向回溯,最后停留在完整的画面。
1、html+css结构很简单,<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<title>乘法口诀</title>
<style>
//每个小块,默认隐藏
#result span{
display:none;
width:60px;
height:25px;
line-height:25px;
font-size:12px;
text-align:center;
border:1px solid #eee;
margin: -1px 0 0 -1px;
}
//最后全部显示每个小块
.idspan span{display:inline-block !important;}
</style>
</head>
<body>
<div id="result"></div>
</body>
</html>
2、js代码,全部封装在一个mul对象中。主要用到了:
- ES6中新特性for-of遍历数组与类数组(dom节点集合)
- 箭头函数
- 模板字符串
- 闭包
- 延迟执行
var mul = {
arr: [1, 2, 3, 4, 5, 6, 7, 8, 9],
str: '',
c: 0,
domResult: document.getElementById("result"),
nodes: document.getElementsByTagName("span"),
//创建内容
create: function () {
for (var i of this.arr)
{
for (var j = 1; j <= i; j++) {
this.str +=`<span > ${j}*${i} =`+(i * j) + '</span> '
}
this.str += '<br>'
}
this.domResult.innerHTML = this.str
//部分浏览器不支持for-of类数组(如节点集合)循环,为其手动添加与数组一致的迭代器方法
mul.nodes[Symbol.iterator] = Array.prototype[Symbol.iterator];
//返回对象本身,方便调用时方法连写。
return mul;
},
//逐个显示
show: function () {
for (var nodespan of this.nodes ){
(nodespan=>{
setTimeout(function () {
nodespan.style.display = 'inline-block'
}, 100 * this.c)
//箭头函数继承了外围作用域的 this 值,所以this,依旧指向mul对象
this.c++
})(nodespan)
}
return mul;
},
//逐个隐藏
hide: function () {
for (var nodespan of this.nodes ){
(nodespan=>{
setTimeout(function () {
nodespan.style.display = ''
}, 100 * this.c + 4500)
this.c--
})(nodespan)
}
return mul;
},
//全部显示出来
ini: function() {
setTimeout(function () {
mul.domResult.setAttribute('class', 'idspan')
}, 9100)
return mul;
}
}
3、调用mul中的方法
mul.create().show().hide().ini()