您的位置 首页 技术

css如何实现开关效果

首先是构思: 我们使用<input type="checkbox">标签来实现这个效果。 checkbox的选中、未选中的特性,刚好对应开关的打开、…

首先是构思:

我们使用<input type="checkbox">标签来实现这个效果。

checkbox的选中、未选中的特性,刚好对应开关的打开、关闭

on:打开 off:关闭

<label for="ck2">  <input type="checkbox" id="ck2">  <span>未选中,则关闭开关</span></label><br><label for="ck1">  <input type="checkbox" id="ck1" checked>  <span>选中,则打开开关</span></label>

效果:

5c9130705213b1a036c5edc97913bd3.png

(推荐教程:CSS入门教程)

开始画出off、on状态的草图

这里要讲解一下,使用了position来实现的定位。有不了解的同学可以打开MDN查看相关知识

<P>off状态草图</P><div class="toggle">  <div class="cookie"></div></div><br><P>on状态草图</P><div class="toggle2">  <div class="cookie2"></div></div>.toggle{  display:inline-block;  position:relative;  height:25px;  width:50px;    border-radius:4px;  background:#CC0000;}.cookie{  position:absolute;  left:2px;  top:2px;  bottom:2px;  width:50%;  background:rgba(230,230,230,0.9);  border-radius:3px;}.toggle2{  display:inline-block;  position:relative;  height:25px;  width:50px;   padding:2px;  border-radius:4px;  background:#66CC33;  }.cookie2{  position:absolute;  right:2px;  top:2px;  bottom:2px;    width:50%;  background:rgba(230,230,230,0.9);  border-radius:3px;}

效果:

2076b62d6aafd9e1f624050fcd5284e.png

然后我们将这两个草图放到label内

<label for="ck4">  <input type="checkbox" id="ck4">  <div class="toggle">    <div class="cookie"></div>  </div></label><br><label for="ck3">  <input type="checkbox" id="ck3" checked>  <div class="toggle2">    <div class="cookie2"></div>  </div></label>

效果:

88761267f147226b1396b624e8645b6.png

结合label和checkbox整理、优化css

<label for="ck5">  <input type="checkbox" id="ck5">  <div class="toggle-finish">    <div class="cookie-finish"></div>  </div></label><br><label for="ck6">  <input type="checkbox" id="ck6" checked>  <div class="toggle-finish">    <div class="cookie-finish"></div>  </div></label>.toggle-finish{  cursor:pointer;  display:inline-block;  position:relative;  height:25px;  width:50px;    border-radius:4px;  background:#CC0000;}.cookie-finish{  position:absolute;  left:2px;  top:2px;  bottom:2px;  width:50%;  background:rgba(230,230,230,0.9);  border-radius:3px;}input:checked + .toggle-finish{  background:#66CC33;  }input:checked + .toggle-finish .cookie-finish{   left:auto;  right:2px;}

效果:

7e1bc897eec873e6ebced9a00cdf929.png

到此为止就已经基本实现一个开关的功能了,记得将input隐藏起来哦。

相关视频教程推荐:css视频教程

以上就是css如何实现开关效果的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/52934.html

为您推荐

返回顶部