你有使用过css的:checked伪类吗?

是的,我使用过 CSS 的 :checked 伪类。:checked 伪类选择器用于选择被选中的 <input> 元素,特别是类型为 radiocheckbox 的元素。

这个伪类非常有用,因为它允许你根据输入元素的选中状态来应用不同的样式。例如,你可以改变选中复选框或单选按钮的颜色、大小或其他视觉属性。

以下是一个简单的示例,演示如何使用 :checked 伪类来改变选中复选框的样式:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>:checked 伪类示例</title>
<style>
  /* 隐藏原始的复选框 */
  input[type="checkbox"] {
    display: none;
  }

  /* 自定义复选框的样式 */
  label {
    display: inline-block;
    width: 20px;
    height: 20px;
    background-color: #ccc;
    margin: 5px;
    position: relative;
  }

  /* 选中状态下的复选框样式 */
  input[type="checkbox"]:checked + label {
    background-color: #4CAF50;
  }

  /* 在选中的复选框中添加一个勾号 */
  input[type="checkbox"]:checked + label:after {
    content: '\2714'; /* 勾号的 Unicode 字符 */
    color: white;
    position: absolute;
    top: 2px;
    left: 6px;
  }
</style>
</head>
<body>
  <input type="checkbox" id="checkbox1">
  <label for="checkbox1"></label>
  <input type="checkbox" id="checkbox2">
  <label for="checkbox2"></label>
</body>
</html>

在这个示例中,我们隐藏了原始的复选框,并使用 label 元素和 CSS 来创建自定义的复选框样式。当复选框被选中时,我们使用 :checked 伪类来改变 label 元素的背景颜色,并在其中添加一个勾号。

posted @ 2024-12-29 06:17  王铁柱6  阅读(14)  评论(0编辑  收藏  举报