HTML+CSS 开发简单组件(四)
手写一个滑块开关
- html部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>滑块开关</title>
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body>
<div class="box" data-field="true">
<!-- 定义包围盒 -->
<div class="suger">
<!-- 设置这三个元素的包围盒 -->
<div class="offLeft"></div>
<!-- 滑块左侧 -->
<div class="show"></div>
<!-- 滑块显示点 -->
<div class="offRight"></div>
<!-- 滑块右侧 -->
</div>
</div>
</body>
<script src="index.js" type="text/javascript" charset="utf-8"></script>
</html>
- css部分
*{
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
font-family: "comic sans ms"
/* 定义基本样式 */
}
body{
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
/* 设定尺寸让内部元素居中,方便观看 */
}
.box{
width: 120px;
height: 48px;
/* 设定尺寸 */
border-radius: 24px;
/* 设定圆角 */
box-shadow: inset 0 0 12px rgba(0,0,0,.2);
/* 设定向内阴影 */
background-color: #eeeeee;
/* 设定背景颜色 */
border: 3px solid #b9bdc8;
/* 设定边线颜色 */
overflow: hidden;
/* 设定超出隐藏 */
position: relative;
}
.suger{
width: calc(200% - 42px);
height: 100%;
position: absolute;
left: 0;
/* left: calc(-50% - 15px); 是off */
/* left: 0; 是on */
transition-duration: .4s;
/* 设定一个过渡效果 */
cursor: pointer;
/* 设定鼠标指针为手型 */
}
.offLeft{
width: 50%;
height: 100%;
/* 设定尺寸 */
position: relative;
/* 设定相对定位 */
background-color: #1890ff;
float: left;
}
.offLeft::before{
content: "on";
/* 设定显示文字 */
position: absolute;
/* 设置绝对定位 */
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* 设定平移居中 */
color: #FFFFFF;
font-size: 22px;
/* 设定文字样式 */
}
.show{
width: 42px;
height: 42px;
/* 设定尺寸,因为上下两个边线占用了6像素,所以减去6像素 */
border-radius: 50%;
/* 设定圆角50%,为圆形 */
box-shadow: inset 0 0 6px rgba(0,0,0,.25),0 2px 4px rgba(0,0,0,.3);
/* 设定一个向内的阴影 */
background-color: #FFFFFF;
/* 设定背景颜色 */
position: absolute;
/* 设定绝对定位 */
top: 0;
left: calc(50% - 21px);
/* 设定位置 */
z-index: 20;
/* 为了防止offRight压住 */
}
.offRight{
width: 50%;
height: 100%;
/* 设定尺寸 */
position: relative;
/* 设定相对定位 */
float: left;
}
.offRight::before{
content: "off";
/* 设定显示文字 */
position: absolute;
/* 设置绝对定位 */
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* 设定平移居中 */
color: #878787;
font-size: 22px;
/* 设定文字样式 */
}
- js部分
(doc=>{
const box = doc.querySelector(".box");
// 获取包围盒
const suger = doc.querySelector(".suger");
// 获取三元素的包围盒
box.addEventListener("click",e=>{
if(box.dataset.field==="true"){
suger.style["left"] = "calc(-50% - 15px)";
box.dataset.field = "false";
}else{
suger.style["left"] = "0px";
box.dataset.field = "true";
}
});
// 给包围盒绑定单击监听事件
})(document)