如何使用HTML+CSS实现选中切换蓝色背景的Win/Mac切换按钮
Win/Mac切换按钮选中效果实现
你现有代码无法实现预期效果的核心原因有两点:一是active选中类错误绑定在了父容器上,无法单独控制两个按钮的样式;二是缺少点击事件逻辑来切换选中状态。按以下步骤修改即可:
修正CSS样式
调整选中态规则,将active类直接作用于按钮本身,同时补充基础交互体验样式:
.main-box { border-style : solid; border-color : #008aff; border-width : 1px; border-radius : 30px; overflow: hidden; } .flex-container { display : flex; flex-wrap : nowrap; } .flex-container>.btn { width : 70px; text-align : center; line-height : 25px; border-radius : 30px; font-size : 20px; background-color: #fff; color: #008aff; cursor: pointer; padding: 4px 0; transition: background-color 0.2s ease, color 0.2s ease; } .flex-container>.btn.active { background-color : #008aff; color: #fff; }
调整HTML结构
将原父容器上的active类移动到默认选中的「Win」按钮上:
<div class="main-box"> <div class="flex-container"> <div class="btn1 btn active">Win</div> <div class="btn2 btn">Mac</div> </div> </div>
添加交互逻辑
引入一段原生JS实现点击切换选中态的功能:
const switchBtns = document.querySelectorAll('.flex-container .btn'); switchBtns.forEach(btn => { btn.addEventListener('click', () => { // 清除所有按钮的选中状态 switchBtns.forEach(item => item.classList.remove('active')); // 给当前点击按钮添加选中态 btn.classList.add('active'); }) })
可选自定义调整
- 不需要切换动画直接删除CSS中的
transition属性即可 - 需要对接业务逻辑时,可在点击事件中通过
btn.textContent获取当前选中的是Win还是Mac - 可自行调整padding、颜色值匹配你的设计稿规范
内容的提问来源于stack exchange,提问作者BGSniper-xll
相关产品推荐
相关产品推荐

