You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS实现仅切换背景色的React滑块式开关按钮

修复滑块式开关按钮:同时显示On/Off文本并正确切换背景色

问题根源

  1. 原代码通过条件渲染仅显示单个文本(On/Off二选一),无法实现并排显示需求
  2. CSS中背景色与伪元素的样式逻辑冲突,导致背景始终呈现蓝色
  3. 文本对齐方式的动态修改进一步加剧了显示异常

修改后的完整代码

React组件代码

import React, { useState } from 'react';
import './styles.css'; 

const App = () => {
  const [isOn, setIsOn] = useState(false);

  const toggleSwitch = () => {
    setIsOn(!isOn);
  };

  return (
    <div className="toggle-container">
      <button
        className={`toggle-button ${isOn ? 'on' : 'off'}`}
        onClick={toggleSwitch}
      >
        <span className="toggle-labels">
          <span className="label-off">Off</span>
          <span className="label-on">On</span>
        </span>
        <span className="toggle-slider"></span>
      </button>
    </div>
  );
};

export default App;

CSS样式代码

.toggle-container {
  display: flex;
  align-items: center;
}

.toggle-button {
  border: 2px solid blue;
  outline: none;
  cursor: pointer;
  width: 100px;
  padding: 10px 0;
  border-radius: 25px;
  font-weight: bold;
  font-size: 16px;
  position: relative;
  background-color: blue;
  transition: background-color 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

/* 开启状态下的按钮背景 */
.toggle-button.on {
  background-color: white;
}

.toggle-labels {
  width: 100%;
  display: flex;
  justify-content: space-around;
  position: relative;
  z-index: 1; /* 确保文本在滑块上方 */
}

.label-off, .label-on {
  transition: color 0.3s ease;
}

/* Off文本颜色控制 */
.toggle-button.off .label-off {
  color: white;
}
.toggle-button.on .label-off {
  color: blue;
}

/* On文本颜色控制 */
.toggle-button.off .label-on {
  color: blue;
}
.toggle-button.on .label-on {
  color: white;
}

/* 滑动块样式 */
.toggle-slider {
  position: absolute;
  top: 2px;
  left: 2px;
  width: calc(50% - 4px);
  height: calc(100% - 4px);
  border-radius: 20px;
  background-color: white;
  transition: left 0.3s ease;
}

/* 开启状态下滑块位置与颜色 */
.toggle-button.on .toggle-slider {
  left: calc(50% + 2px);
  background-color: blue;
}

关键修改说明

  • 固定双文本布局:移除条件渲染逻辑,在按钮内同时放置Off和On标签,通过CSS控制颜色切换
  • 清晰的状态联动:用on/off类统一控制按钮背景色、文本颜色和滑块位置,避免样式冲突
  • 平滑过渡动画:给背景色、文本颜色和滑块位置都添加了0.3秒的过渡动画,确保切换过程流畅自然
  • 层级管理:通过z-index确保文本始终显示在滑块上方,避免被遮挡

内容的提问来源于stack exchange,提问作者Sougata Mukherjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 16:25:36