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

如何在HTML/CSS中区分不同Checkbox实现点赞点灭功能

解决点赞/点灭按钮的颜色冲突问题

你说得没错,问题确实出在两个重复的input[type=checkbox]:checked规则上——CSS中相同优先级的选择器,后面的声明会完全覆盖前面的,所以不管点哪个复选框,都会应用红色背景。

解决思路很简单:利用复选框所在的父容器类(.greencheckbox和.redcheckbox)来区分两个复选框,给各自的checked状态添加带父类前缀的选择器,这样就能分别控制颜色了。

修改后的CSS代码如下:

body {}

.main_box {
  background-color: #320082;
  height: 500px;
  width: 250px;
  border: 2px solid #000000;
  border-radius: 20px;
}

h1 {
  text-align: center;
  font-size: 40px;
  color: #ff4da6;
}

h2 {
  font-size: 16px;
  text-align: center;
  color: aliceblue;
}

.glow {
  color: #fff;
  text-align: center;
  animation: glow 1s ease-in-out infinite alternate;
}

.greencheckbox {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.redcheckbox {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

input[type=checkbox] {
  appearance: none;
  height: 100px;
  width: 100px;
  background-color: rgb(175, 175, 175);
  border-radius: 50%;
}

.thumb {
  position: absolute;
  font-size: 35px;
  color: white;
}

/* 修改这里的选择器,添加父容器类前缀 */
.greencheckbox input[type=checkbox]:checked {
  background-color: rgb(0, 160, 0);
}

.redcheckbox input[type=checkbox]:checked {
  background-color: rgb(160, 0, 0);
}

@-webkit-keyframes glow {
  from {
    text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #e60073, 0 0 40px #e60073, 0 0 50px #e60073, 0 0 60px #e60073, 0 0 70px #e60073;
  }
  to {
    text-shadow: 0 0 20px #fff, 0 0 30px #ff4da6, 0 0 40px #ff4da6, 0 0 50px #ff4da6, 0 0 60px #ff4da6, 0 0 70px #ff4da6, 0 0 80px #ff4da6;
  }
}

原理说明

  • 原来的两个input[type=checkbox]:checked选择器优先级完全相同,后声明的红色规则会覆盖绿色规则。
  • 添加父容器类前缀后,.greencheckbox input[type=checkbox]:checked和.redcheckbox input[type=checkbox]:checked的优先级比单纯的input[type=checkbox]:checked更高,而且各自对应不同的复选框,不会再互相覆盖。

这样修改后,点击点赞按钮(.greencheckbox内的复选框)会显示绿色背景,点击点灭按钮(.redcheckbox内的复选框)会显示红色背景,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:45:07