jsrun在线地址:http://jsrun.net/uTLKp
Html代码:
<div id="father">
<div class="coming" id="child1">偶数点击</div>
<div class="coming hided" id="child2">奇数点击</div>
<p style="padding-top: 70px;">==============================</p>
当前替换boolean:<div id="shownum">true</div>
<button onclick="changeShow()">替换</button>
</div>
css代码:
.father{
position: relative;
}
.coming{
animation-name:showing_animation;
animation-iteration-count:1;
animation-timing-function:ease;
animation-duration:1.5s;
animation-fill-mode:forwards;/*动画结束后保留最后一个样式*/
}
.hiding{
animation-name:noshowing_animation;
animation-iteration-count:1;
animation-timing-function:ease;
animation-duration:1s;
animation-fill-mode:forwards;/*动画结束后保留最后一个样式*/
}
@keyframes showing_animation
{
0% {opacity:0;}
100% {opacity:1;}
}
@keyframes noshowing_animation
{
0% {opacity:1;}
100% {opacity:0;}
}
.child1{
position: absolute;
color: red;
height: 50px;
z-index: 1;
display: grid;
place-items: center;
padding:10px 15px;
}
.child2{
position: absolute;
color: green;
height: 50px;
z-index:2;
display: grid;
place-items: center;
padding:10px 15px;
}
.child1.hided,.child2.hided{
display: none;
}
js代码:
let a = true;
changeShow=()=>{
a = !a;
document.getElementById("shownum").innerText=a;
let father = document.getElementById("father");
let child1 = document.getElementById("child1");
let child2 = document.getElementById("child2");
/**初始状态:
* #child1: coming
* #child2: coming hided
*/
if(a==false){//false分支---应该显示“奇数点击”
let arr = Array.from(child1.classList);//{"0":"coming"}转数组["coming"]
if(arr.indexOf("hiding")==-1){
child1.classList.add("hiding");//#child1: coming hiding
}
child2.classList.remove("hided");
child2.classList.remove("hiding");
}else{//true分支---应该显示“偶数点击”
let arr = Array.from(child2.classList);
if(arr.indexOf("hiding")==-1){
child2.classList.add("hiding");#child2: coming hiding
}
child1.classList.remove("hiding");//#child1: coming
}
}
解析:
通过"z-index"使得“奇数点击”位于“偶数点击”上层,默认展示时通过本质为“display:none”的"hided"类使得“奇数点击”既不可见又不占据文档流。
通过"子绝父相"使得“奇数点击”与“偶数点击”重合。
“coming”类提供了元素渲染时的淡入动画,并通过“animation-fill-mode:forwards;”保留了动画最后一帧的样式,在“showing_animation”淡入动画已经进行并停止在最后一帧时,加上“hiding”类,便会[继续]进行"noshowing_animation"淡出动画。
【这里笔者也不是很清楚原理,个人推测是“重新”】:在同时拥有coming和hiding类的时候,若移除hiding类便会[重新]进行coming动画。
(有个小小的个人优化,淡出持续1s淡入持续1.5s,消失比显现的快,使人更早的看到下一个状态的内容)
用true和false来规划页面按钮点击次数的两种情况。
Array.from来数组化[dom元素].classList所返回的类数组对象,若不存在指定css类则该数组对指定css类名的indexOf判定将会返回-1,进入此时的逻辑再进行上述的add操作。但是remove操作不需要判断是否存在。