css两个开关按钮切换

admin 轻心小站 关注 LV.19 运营
发表于前端技术学习版块 css,教程

在Web开发中,常常会遇到需要使用开关按钮切换的场景。这时,我们可以使用CSS来实现这个功能。以下是两个基本的开关按钮切换的代码示例:.switch { position: relative; dis

在Web开发中,常常会遇到需要使用开关按钮切换的场景。这时,我们可以使用CSS来实现这个功能。以下是两个基本的开关按钮切换的代码示例:

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  display: none;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
} 

以上代码实现了一个基本的开关按钮切换功能。在HTML中,我们需要使用input标签,在CSS中使用伪类选择器:checked和:before来控制样式变化。

.switch {
  position: relative;
  display: inline-block;
  width: 70px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  border-radius: 34px;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  border-radius: 50%;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(35px);
  -ms-transform: translateX(35px);
  transform: translateX(35px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
} 

以上代码实现了另一个基本的开关按钮切换功能。我们可以看到,在这个示例中,使用了-webkit-transition和-ms-transition来控制样式变化的过程。此外,还可以使用.round类来控制开关按钮的形状。

文章说明:

本文原创发布于探乎站长论坛,未经许可,禁止转载。

题图来自Unsplash,基于CC0协议

该文观点仅代表作者本人,探乎站长论坛平台仅提供信息存储空间服务。

评论列表 评论
发布评论

评论: css两个开关按钮切换

粉丝

0

关注

0

收藏

0

已有0次打赏