美文网首页
js 拖动滑块验证

js 拖动滑块验证

作者: Peter_2B | 来源:发表于2020-08-19 13:58 被阅读0次
    <div class="wrapper">
    
        <div class="btn"></div>
    
        <p class="text">请向右滑动</p>
    
        <div class="bg"></div>
    </div>
    
    <script>
      var wrapper = document.querySelector('.wrapper');
      var btn = document.querySelector('.btn');
      var bg = document.querySelector('.bg');
      var left = null;
    
      btn.onmousedown = function(event) {
          console.log(event.clientX);
          var downX = event.clientX;      //触发事件时 鼠标相对于浏览器的x距离
    
          document.onmousemove = function(e) {
              var moveX = e.clientX;
              console.log(moveX);        //触发事件时 鼠标相对于浏览器的x距离
    
              left = moveX - downX;      //点击down移动move 滑动的距离
    
              if(left < 0){ left = 0 }
              if(left > wrapper.offsetWidth-btn.offsetWidth ){      //还需要减去btn的宽度
                 left = wrapper.offsetWidth-btn.offsetWidth; 
              }  
              btn.style.left = left + 'px';
              bg.style.width = left + 'px';
    
              if(left >= wrapper.offsetWidth-btn.offsetWidth ){
                    //ajax请求 判断是否可以登录成功
                    wrapper.style.color = 'white';
                    btn.onmousedown = null;    //防止 btn再次被点击
                    document.onmousemove = null;
                    document.onmouseup = null;
              }
            }
        }
    
        // btn.onmousedown    //不能只监听滑块上的鼠标抬起; 在整个文档上鼠标抬起体验更好
        document.onmouseup = function(event) {
            document.onmousemove = null;
            if(left < wrapper.offsetWidth-btn.offsetWidth){
                  btn.style.left = 0;
                  bg.style.width = 0;
                  wrapper.style.color = 'black';
            }
            console.log('鼠标抬起'+event.clientX);
            document.onmouseup = null;
        }
    </script>
    
    <style>
    *{
        margin: 0;
        padding: 0;
    }
    body{
        user-select: none;  /***文本不被选中(拖动的时候里面的文字会被选中)***/
    }
    .wrapper{
        position: relative;
        width: 300px;
        height: 34px;
        line-height: 34px;
        background: #fff;
        border: 1px solid #ccc;
        margin: 0 auto;
    }
    .bg{
        position: absolute;
        height: 100%;
        width: 0;
        background: #7ac23c;
        z-index: 1;
    }
    .text{
        position: absolute;
        width: 100%;
        margin: 0;
        text-align: center;
        z-index: 2;
    }
    .btn{
        position: absolute;
        top: 0;
        width: 40px;
        height: 32px;
        z-index: 3;
        border: 1px solid #ccc;
        background: #fff url(data:img/jpg;base64) center no-repeat;   /***btn背景图片***/
        cursor: pointer;
    }
    </style>
    

    相关文章

      网友评论

          本文标题:js 拖动滑块验证

          本文链接:https://www.haomeiwen.com/subject/ywfkjktx.html