js实现移动端图片滑块验证功能


Posted in Javascript onSeptember 29, 2020

之前写过一篇uniapp框架的滑块验证,今天抽个空用原生js实现这个功能,pc端暂时不做,因为pc端只要把touch事件改成mouse事件就能实现,这里就不再重复写了。
(最新完美版本,js+canvas实现,兼容pc,ie9和移动,js+cavans实现图片滑块验证)

老样子,还是先看效果

js实现移动端图片滑块验证功能

原理和上篇uniapp的滑块一样,不一样的是这里是纯js实现,代码是全部是自己写的,有不清楚的可以留言。

下面是全部代码:

html:

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
 
 
    .sliderModel {
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      display: none;
    }
 
    .title {
      width: 100%;
      height: 60px;
      font-size: 18px;
      color: #333;
      display: flex;
      align-items: center;
      justify-content: center;
    }
 
    .cont {
      position: relative;
      background: #fff;
      width: 300px;
      border-radius: 8px;
      overflow: hidden;
      padding-bottom: 20px;
    }
 
    .imgWrap {
      position: relative;
      width: 280px;
      height: 150px;
      border-radius: 8px;
      margin: 0 auto;
      overflow: hidden;
    }
 
    #sliderRefresh {
      position: absolute;
      top: 20px;
      right: 30px;
      cursor: pointer;
      color: green;
    }
 
    .img {
      display: block;
      width: 100%;
      height: 100%;
    }
 
    .sliderOver {
      position: absolute;
      left: 0;
      top: 0;
      width: 50px;
      height: 50px;
      background: #ddd;
      box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.3);
    }
 
    .smartImg {
      position: absolute;
      z-index: 2;
      left: 0;
      top: 0;
      width: 50px;
      height: 50px;
      overflow: hidden;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
    }
 
    .simg {
      position: absolute;
      display: block;
      width: 280px;
      height: 150px;
    }
 
 
 
 
    .sliderBox {
      width: 280px;
      margin: 10px auto 0;
      height: 36px;
      position: relative;
    }
 
    .sliderF {
      width: 100%;
      height: 100%;
      z-index: 3;
    }
 
    .sliderS {
      cursor: pointer;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 2;
      height: 36px;
      width: 36px;
      background: #007cff;
      border-radius: 36px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
 
    .icon {
      width: 20px;
      height: 20px;
 
    }
 
 
    .bgC {
      position: absolute;
      z-index: 1;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 100%;
      height: 30px;
      border-radius: 30px;
      line-height: 30px;
      font-size: 14px;
      color: #999999;
      box-shadow: inset 0 0 4px #ccc;
      text-align: center;
      overflow: hidden;
    }
 
    .bgC_left {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 0;
      height: 28px;
      border-top-left-radius: 28px;
      border-bottom-left-radius: 28px;
      line-height: 28px;
      font-size: 14px;
      background-color: #eee;
      box-shadow: inset 0 0 4px #ccc;
      text-align: center;
    }
 
 
    .showMessage {
      text-align: center;
      font-size: 14px;
      height: 30px;
      line-height: 30px;
    }
 
    #closeBtn {
      position: fixed;
      z-index: 10;
      bottom: 10px;
      left: 50%;
    }
  </style>
</head>
 
<body>
  <div id="clickBtn">点击</div>
  <div class="sliderModel">
    <div class="cont">
      <div class="title">图形验证</div>
      <div id="sliderRefresh">刷新</div>
      <div class="imgWrap" id="imgWrap">
        <img class="img" src="" />
        <div class="sliderOver" id="sliderOver"></div>
        <div class="smartImg" id="smartImg">
          <img class="simg" src="" />
        </div>
      </div>
      <div class="sliderBox">
        <div class="sliderF" id="slider">
          <div class="sliderS" id="sliderBtn">
            <img class="icon" src="images/slider/sangangy.png" />
          </div>
        </div>
        <div class="bgC">
          拖动左边滑块完成上方拼图
          <div class="bgC_left" id="bgC_left"></div>
        </div>
      </div>
      <div class="showMessage">
 
      </div>
    </div>
  </div>
  <div id="closeBtn">关闭</div>
 
</body>
<script src="slider.js"></script>
<script>
  var object = {
    bImg: 'imgWrap',
    sImg: 'smartImg',
    sImgOver: 'sliderOver',
    sliderF: 'slider',
    sliderBtn: 'sliderBtn',
    sliderBg: 'bgC_left',
    refreshBtn: 'sliderRefresh',
    range: 5,
    imgArr: ['images/sliderz/1.jpg', 'images/sliderz/2.jpg', 'images/sliderz/3.jpg', 'images/sliderz/4.jpg',
      'images/sliderz/5.jpg'
    ],
    refreshCallback: function (e) {
      var showMessage = document.getElementsByClassName('showMessage')[0];
      showMessage.innerHTML = "";
      showMessage.style.color = "#333";
    },
    callback: function (e) {
      var showMessage = document.getElementsByClassName('showMessage')[0];
      if (!e) {
        showMessage.innerHTML = "验证失败,请重新验证";
        showMessage.style.color = "red";
      } else {
        showMessage.innerHTML = "验证成功!";
        showMessage.style.color = "green";
      }
    },
  }
  var mSlider = null;
  document.getElementById('clickBtn').onclick = function () {
    document.getElementsByClassName('sliderModel')[0].style.display = "flex";
    mSlider = new window.mobileSlider(object)
  }
  document.getElementById('closeBtn').onclick = function () {
    document.getElementsByClassName('sliderModel')[0].style.display = "none";
  }
</script>
 
</html>

js部分(slider.js)

(function () {
 
  function mobileSlider(params) {
    var object = {
      bImg: params.bImg, //大图片的盒子
      sImg: params.sImg, //图片上的小图片
      sImgOver: params.sImgOver, //图片上的占位区域
      sliderF: params.sliderF, //滑块的父元素
      sliderBtn: params.sliderBtn, //滑块
      sliderBg: params.sliderBg, //滑块滑动过程中的背景块
      refreshBtn: params.refreshBtn, //刷新按钮
      range: params.range, //验证通过的运行范围值
      imgArr: params.imgArr, //图片数组
      refreshCallback: params.refreshCallback, //刷新回调
      callback: params.callback //验证回调函数,true为成功,false为失败
    };
 
    var sliderF = document.getElementById(object.sliderF);
    var sliderBtn = document.getElementById(object.sliderBtn);
    var sliderBg = document.getElementById(object.sliderBg);
    var sImg = document.getElementById(object.sImg);
    var bImg = document.getElementById(object.bImg);
    var sImgOver = document.getElementById(object.sImgOver);
    var refreshBtn = document.getElementById(object.refreshBtn);
    var max_left = sliderF.offsetWidth - sliderBtn.offsetWidth;
    var sImgBeginLeft = 0;
 
 
    function refresh() {
      sliderBtn.style.left = sliderBg.style.width = 0;
      sImgBeginLeft = 0;
      var ram = Math.random();
      var imgIndex = Math.floor(object.imgArr.length * ram);
      var imgSrc = object.imgArr[imgIndex];
      bImg.getElementsByClassName('img')[0].src = sImg.getElementsByClassName('simg')[0].src = imgSrc;
      sImgOver.style.left = Math.floor(bImg.offsetWidth / 2 + bImg.offsetWidth / 2 * ram - sImgOver.offsetWidth - 6) + "px";
      sImg.style.left = sImgBeginLeft = Math.floor((bImg.offsetWidth / 2 - sImgOver.offsetWidth) * ram) + "px";
      sImgOver.style.top = sImg.style.top = Math.floor((bImg.offsetHeight - sImgOver.offsetWidth - 10) * ram + 10) + "px";
      sImg.getElementsByClassName('simg')[0].style.left = -Math.floor(bImg.offsetWidth / 2 + bImg.offsetWidth / 2 * ram - sImgOver.offsetWidth - 6) + "px";
      sImg.getElementsByClassName('simg')[0].style.top = -Math.floor((bImg.offsetHeight - sImgOver.offsetWidth - 10) * ram + 10) + "px";
      object.refreshCallback(true)
    }
    refresh();
 
    sliderBtn.ontouchstart = function (e) {
      var ev = e || window.event
      var downX = ev.touches[0].pageX;
      var sImgLeft = parseInt(sImg.style.left);
      this.ontouchmove = function (e) {
        var ev = e || window.event;
        var leftX = ev.touches[0].pageX - downX;
        leftX = leftX < 0 ? 0 : (leftX < max_left ? leftX : max_left)
        sliderBtn.style.left = leftX + 'px';
        sliderBg.style.width = leftX + sliderBtn.offsetWidth / 2 + "px";
        sImg.style.left = leftX + sImgLeft + "px";
      }
      this.ontouchend = function (e) {
        this.ontouchmove = null; //移除移动事件
        var sImgLeft = parseInt(sImg.style.left);
        var sImgOverLeft = parseInt(sImgOver.style.left);
        if (Math.abs(sImgOverLeft - sImgLeft) < object.range) {
          object.callback && object.callback(true)
        } else {
          object.callback && object.callback(false)
          var timer = null,
            step = 10;
          var sliderBtnLeft = parseInt(sliderBtn.style.left)
          timer = setInterval(function () {
            sliderBtnLeft -= step;
            step += 5;
            if (sliderBtnLeft <= 0) {
              clearInterval(timer);
              sliderBtnLeft = 0;
              sliderBtn.style.left = sliderBg.style.width = 0;
              sImg.style.left = parseInt(sImgBeginLeft) + "px"
            }
            sliderBtn.style.left = sliderBg.style.width = sliderBtnLeft + "px";
            sImg.style.left = sliderBtnLeft + parseInt(sImgBeginLeft) + "px"
          }, 20)
 
        }
      }
    };
 
 
 
    refreshBtn.ontouchstart = function () {
      refresh()
    }
 
  }
 
  window.mobileSlider = mobileSlider;
})()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。 

Javascript 相关文章推荐
用tip解决Ext列宽度不够的问题
Dec 13 Javascript
ExtJS 工具栏 分页事件参数
Mar 05 Javascript
javascript如何创建表格(javascript绘制表格的二种方法)
Dec 10 Javascript
jQuery监控文本框事件并作相应处理的方法
Apr 16 Javascript
javascript实现动态表头及表列的展现方法
Jul 14 Javascript
详解JavaScript中jQuery和Ajax以及JSONP的联合使用
Aug 13 Javascript
Bootstrap源码解读排版(1)
Dec 23 Javascript
jQuery实现的无缝广告图片左右滚动功能详解
Dec 24 Javascript
vue使用stompjs实现mqtt消息推送通知
Jun 22 Javascript
详解vue中$nextTick和$forceUpdate的用法
Dec 11 Javascript
vue-amap根据地址回显地图并mark的操作
Nov 03 Javascript
Vue elementUI表单嵌套表格并对每行进行校验详解
Feb 18 Vue.js
js+cavans实现图片滑块验证
Sep 29 #Javascript
如何利用JS将手机号中间四位变成*号
Sep 29 #Javascript
原生JavaScript实现刮刮乐
Sep 29 #Javascript
原生JavaScript实现拖动校验功能
Sep 29 #Javascript
使用JavaScript实现贪吃蛇游戏
Sep 29 #Javascript
解决idea开发遇到javascript动态添加html元素时中文乱码的问题
Sep 29 #Javascript
Openlayers3实现车辆轨迹回放功能
Sep 29 #Javascript
You might like
咖啡知识 咖啡养豆要养多久 排气又是什么
2021/03/06 新手入门
php正则表达式(regar expression)
2011/09/10 PHP
关于ob_get_contents(),ob_end_clean(),ob_start(),的具体用法详解
2013/06/24 PHP
PHP实现的XML操作类【XML Library】
2016/12/29 PHP
php的PDO事务处理机制实例分析
2017/02/16 PHP
PHP常用工具函数小结【移除XSS攻击、UTF8与GBK编码转换等】
2019/04/27 PHP
PHP数组访问常用方法解析
2020/09/05 PHP
基于jQuery的遍历同id元素 并响应事件的代码
2012/06/14 Javascript
浅析tr的隐藏和显示问题
2014/03/05 Javascript
jquery选择器原理介绍($()使用方法)
2014/03/25 Javascript
jQuery如何获取同一个类标签的所有值(默认无法获取)
2014/09/25 Javascript
深入理解JavaScript系列(17):面向对象编程之概论详细介绍
2015/03/04 Javascript
详解js界面跳转与值传递
2016/11/22 Javascript
JQuery异步提交表单与文件上传功能示例
2017/01/12 Javascript
Vue2.0父组件与子组件之间的事件发射与接收实例代码
2017/09/19 Javascript
在小程序/mpvue中使用flyio发起网络请求的方法
2018/09/13 Javascript
[原创]微信小程序获取网络类型的方法示例
2019/03/01 Javascript
js纯前端实现腾讯cos文件上传功能的示例代码
2019/05/14 Javascript
JavaScript变量作用域及内存问题实例分析
2019/06/10 Javascript
Python画图学习入门教程
2016/07/01 Python
TensorFlow实现Softmax回归模型
2018/03/09 Python
使用python采集脚本之家电子书资源并自动下载到本地的实例脚本
2018/10/23 Python
django将数组传递给前台模板的方法
2019/08/06 Python
python 回溯法模板详解
2020/02/26 Python
pyMySQL SQL语句传参问题,单个参数或多个参数说明
2020/06/06 Python
Python生成器generator原理及用法解析
2020/07/20 Python
HTML5 history新特性pushState、replaceState及两者的区别
2015/12/26 HTML / CSS
全球知名的珠宝首饰品牌:Kay Jewelers
2018/02/11 全球购物
浙大网新C/C++面试解惑
2015/05/27 面试题
linux面试题参考答案(9)
2015/01/07 面试题
民族团结先进个人材料
2014/02/05 职场文书
党校培训自我鉴定范文
2014/04/10 职场文书
小学校长竞聘演讲稿
2014/05/16 职场文书
十八大宣传标语
2014/10/09 职场文书
2014年学生管理工作总结
2014/12/20 职场文书
2015年学校体育工作总结
2015/04/22 职场文书