Open david2tdw opened 4 years ago
关键点:
:checked
伪类,加上 <label for>
实现纯 CSS 捕获点击事情。原理同#138
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>伪元素 checked 实现纯 CSS 方式控制动画的暂停与播放</title>
<style>
input {
display: none;
}
.btn {
width: 200px; /* 单行元素不需要设置高度,默认会垂直居中,通过padding控制内边距 */
border: 1px solid #ddd;
margin: 10px auto;
padding: 10px;
text-align: center;
}
.btn:hover {
background-color: #ddd;
color: #333;
}
#stop:checked ~ .animation {
animation-play-state: paused;
}
#play:checked ~ .animation {
animation-play-state: running;
}
.animation {
background-color: deeppink;
width: 200px;
height: 200px;
animation: move 6s linear infinite alternate; /* alternate 来回运动 */
}
@keyframes move {
0% {
}
100% {
transform: translate(200px, 0);
}
}
</style>
</head>
<body>
<input type="radio" name="playAnimation" id="stop" />
<input type="radio" name="playAnimation" id="play" />
<div class="box">
<label for="stop">
<div class="btn">stop</div>
</label>
<label for="play">
<div class="btn">play</div>
</label>
</div>
<div class="animation"></div>
</body>
</html>
伪元素 checked 实现纯 CSS 方式控制动画的暂停与播放