以下为实现注册时未勾选阅读相关协议时的复选框抖动示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>复选框抖动</title>
<style>
/* 关键帧 */
@keyframes shake {
0% {
transform: translateX(0);
}
10%,
30%,
50%,
70%,
90% {
transform: translateX(-5px);
}
20%,
40%,
60%,
80% {
transform: translateX(5px);
}
100% {
transform: translateX(0);
}
}
/* 动画class样式 */
.shake-animation {
animation: shake 0.5s;
}
#read-check {
display: none;
}
/* + 相邻兄弟选择器 (只对同级的下一个标签有效) */
#read-check+label {
display: block;
width: 20px;
height: 20px;
cursor: pointer;
background: #fff;
border: 1px solid #000;
border-radius: 5px;
text-align: center;
font-size: 16px;
color: #fff;
}
#read-check:checked+label {
background-color: #1296db;
}
</style>
</head>
<body>
<button class="btn">复选框抖动动画</button>
<input id="read-check" type="checkbox" placeholder="none">
<!-- label:扩大选择范围,这里用作代替复选框显示(样式作用) 注意:label上的for属性对应复选框id -->
<label for="read-check">✔</label>
<script>
// 获取按钮设置点击事件
document.querySelector('.btn').onclick = function () {
// 获取for属性对应id为read-check的label标签
let checkboxLabel = document.querySelector('label[for="read-check"]');
// 给复选框标签添加自定义class动画样式
checkboxLabel.classList.add('shake-animation');
// 延时器 只执行一次 参数1: 执行函数 参数2: 延迟时间(毫秒)
setTimeout(function () {
checkboxLabel.classList.remove('shake-animation');
}, 500);
}
</script>
</body>
</html>
以上代码主要是为了方便自己查看,如果有任何不足之处,请指出。
参考资料: