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

如何实现自定义toggle开关每次点击时切换为随机颜色

随机色开关实现方法

不用引入第三方库,原生JS配合CSS自定义属性就能实现需求,比额外加.enabled/.disabled状态类的方案简洁很多。

第一步:调整原有CSS代码

把选中态写死的背景色替换成CSS变量引用,留个默认色兜底就行,其他原有样式逻辑完全不用动:

.toggle {
  --width: 80px;
  --height: calc(var(--width) / 3);
  /* 新增激活色自定义属性,默认值保留原有的蓝色 */
  --active-color: #2196F3;

  position: relative;
  display: inline-block;
  width: var(--width);
  height: var(--height);
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
  border-radius: var(--height);
  cursor: pointer;
}

.toggle input {
  display: none;
}

.toggle .slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: var(--height);
  background-color: #ccc;
  transition: all 0.4s ease-in-out;
}

.toggle .slider::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: calc(var(--height));
  height: calc(var(--height));
  border-radius: calc(var(--height) / 2);
  background-color: #fff;
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
  transition: all 0.4s ease-in-out;
}

.toggle input:checked+.slider {
  /* 替换原来写死的#2196F3为变量引用 */
  background-color: var(--active-color);
}

.toggle input:checked+.slider::before {
  transform: translateX(calc(var(--width) - var(--height)));
}

第二步:添加少量原生JS逻辑

监听开关的状态变化事件,每次开关打开时生成随机十六进制颜色,更新对应开关的CSS变量值即可:

// 遍历页面所有开关组件
document.querySelectorAll('.toggle input[type="checkbox"]').forEach(toggle => {
  toggle.addEventListener('change', function() {
    if (this.checked) {
      // 生成随机十六进制颜色值
      const randomColor = '#' + Math.floor(Math.random() * 16777215)
        .toString(16)
        .padStart(6, '0');
      // 把随机色赋值给当前开关的自定义属性
      this.parentElement.style.setProperty('--active-color', randomColor);
    }
  })
})

可选调整方向

  • 如果需要关闭开关时也切换随机灰色,可以在判断分支的else里生成灰调区间的随机色,给滑块默认背景也绑定一个CSS变量动态赋值
  • 如果担心随机生成的颜色太浅和白色滑块辨识度不够,可以在颜色生成逻辑里加亮度校验,过滤掉过亮或者过饱和的颜色

内容的提问来源于stack exchange,提问作者Corbin Riley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 08:54:20