模仿手机解锁滑动,点击向右滑动完毕即可显示解锁成功。
程序详解
1.点击和松开事件
2. 未解锁之前显示的样式和背景色
3. 解锁之后显示的样式和背景色
4. 滑动完毕后才能解锁
图片演示
原始界面
点击滑动后
解锁成功
下面我们跟随我一起来欣赏一下代码
代码演示
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title></title><!--注:iconfont语法,即矢量图标--><link rel="stylesheet" href="font/iconfont.css"><style>*{padding: 0;margin: 0;}#box{position: relative;width: 300px;height: 40px;margin: 0 auto;margin-top: 10px; background-color: #e8e8e8;box-shadow: 1px 1px 5px rgba(0,0,0,0.2);}.groundcolor{position: absolute;left:0;top:0;width:40px;height: 40px;background-color: lightblue;}.text{position: absolute;width: 100%;height: 40px;line-height: 40px;font-size: 14px;color: #000;text-align: center;}.slider{position: absolute;left:0;top:0;width: 50px;height: 38px;border: 1px solid #ccc;background: #fff;text-align: center;cursor: move;}.slider>i{position: absolute;top:50%;left:50%;transform: translate(-50%,-50%);}.slider.active>i{color:green;}</style>
</head>
<body><div id="box" onselectstart="return false;"><div class="groundcolor"></div><div class="text" >滑动解锁</div><!--添加相应字体图标的类名即可--><div class="slider"><i class="iconfont icon-double-right"></i></div></div> <script>//获取元素function getEle(selector){return document.querySelector(selector);}var box = getEle("#box"),//背景色bgColor = getEle(".groundcolor"),txt = getEle(".text"),slider = getEle(".slider"),icon = getEle(".slider>i"),//滑动的距离successMoveDistance = box.offsetWidth- slider.offsetWidth,downX,//是否解锁成功isSuccess = false;slider.onmousedown = mousedownHandler;//鼠标按下function mousedownHandler(e){bgColor.style.transition = "";slider.style.transition = "";var e = e || window.event || e.which;downX = e.clientX;//鼠标按下移动和松开document.onmousemove = mousemoveHandler;document.onmouseup = mouseupHandler;};//移动的距离设置function getOffsetX(offset,min,max){if(offset < min){offset = min;}else if(offset > max){offset = max;}return offset;}//鼠标移动事件function mousemoveHandler(e){var e = e || window.event || e.which;var moveX = e.clientX;var offsetX = getOffsetX(moveX - downX,0,successMoveDistance);bgColor.style.width = offsetX + "px";slider.style.left = offsetX + "px";if(offsetX == successMoveDistance){success();}//滑块水平滑动e.preventDefault();};//鼠标松开事件function mouseupHandler(e){if(!isSuccess){bgColor.style.width = 0 + "px";slider.style.left = 0 + "px";bgColor.style.transition = "width 0.8s linear";slider.style.transition = "left 0.8s linear";}document.onmousemove = null;document.onmouseup = null;};//解锁成功的方法function success(){isSuccess = true;txt.innerHTML = "解锁成功";bgColor.style.backgroundColor ="lightgreen";slider.className = "slider active";icon.className = "iconfont icon-xuanzhong";//成功时,鼠标按下事件和鼠标移动事件slider.onmousedown = null;document.onmousemove = null;};</script>
</body>
</html>