如何用JavaScript在Toggle Switch关闭时停止CSS Spinner
用切换开关控制CSS加载动画的启停/显示隐藏
先修正你的HTML结构
你的原始代码里缺少切换开关的核心<input>元素,补全后的完整HTML结构如下:
<!-- 切换开关容器 --> <label class="switch"> <input type="checkbox" class="switch-input" checked> <span class="slider round"></span> </label> <!-- 加载动画容器 --> <div class="spin"></div>
修正后的CSS代码
修复原始CSS的语法错误,并完善圆角样式:
@keyframes spinner { 0% { transform: translate3d(-50%, -50%, 0) rotate(0deg); } 100% { transform: translate3d(-50%, -50%, 0) rotate(360deg); } } .switch { position: relative; display: inline-block; width: 55px; height: 28px; } /* 隐藏原生复选框 */ .switch-input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 28px; } .slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; } .switch-input:checked + .slider { background-color: #2196F3; } .switch-input:focus + .slider { box-shadow: 0 0 1px #2196F3; } .switch-input:checked + .slider:before { transform: translateX(26px); } .spin::before { animation: 1.5s linear infinite spinner; animation-play-state: var(--animation-state, running); border: solid 5px #cfd0d1; border-bottom-color: #1c87c9; border-radius: 50%; content: ""; height: 20px; width: 20px; position: absolute; top: 26%; left: 35%; transform: translate3d(-50%, -50%, 0); will-change: transform; }
JavaScript实现方案
提供两种常用实现方式,按需选择:
方式1:开关关闭时停止旋转,打开时恢复
通过CSS变量控制动画播放状态:
// 获取开关和动画元素 const switchInput = document.querySelector('.switch-input'); const spinElement = document.querySelector('.spin'); // 监听开关状态变化 switchInput.addEventListener('change', function() { spinElement.style.setProperty('--animation-state', this.checked ? 'running' : 'paused'); });
方式2:开关关闭时隐藏动画,打开时显示
通过控制元素display属性实现:
const switchInput = document.querySelector('.switch-input'); const spinElement = document.querySelector('.spin'); switchInput.addEventListener('change', function() { spinElement.style.display = this.checked ? 'block' : 'none'; });
注意事项
- 把JS代码放在HTML的
</body>标签前,或者用DOMContentLoaded事件包裹,确保页面元素加载完成后再执行代码 - 两种方式可根据需求选择:方式1保留元素但停止动画,方式2直接隐藏元素
内容的提问来源于stack exchange,提问作者Farid
相关产品推荐
相关产品推荐

