JQuery模拟常见的拖拽验证

css部分

<style>
        #drag{ 
            position: relative;
            background-color: #e8e8e8;
            width: 300px;
            height: 34px;
            line-height: 34px;
            text-align: center;
            margin: 50px auto;
        }
        #drag .handler{
            position: absolute;
            top: 0px;
            left: 0px;
            width: 40px;
            height: 32px;
            border: 1px solid #ccc;
            cursor: move;
        }
        .handler_bg{
            background: #fff url("img/1.png") no-repeat center;
        }
        .handler_ok_bg{
            background: #fff url("img/2.png") no-repeat center;
        }
        #drag .drag_bg{
            background-color: #7ac23c;
            height: 34px;
            width: 0px;
        }
        #drag .drag_text{
            position: absolute;
            top: 0px;
            width: 300px;
        }
    </style>

html部分

<div id="drag">
        <div class="drag_bg"></div>
        <div class="drag_text">拖动滑块验证</div>
        <div class="handler handler_bg"></div>
    </div>

JQuery部分

<script>
        $(function(){
            $(".handler").on("mousedown",function(e){
                var disX = e.clientX - $("#drag").offset().left;
                var maxWidth = $("#drag").width() - $(".handler").width();
                $(document).on("mousemove",function(e){
                    var x = e.clientX - $("#drag").offset().left - disX;
                    x = Math.max(Math.min(x,maxWidth),0);
                    $(".handler").css("left",x);
                    $(".drag_bg").width(x);
                    if(x == maxWidth){
                        $(".handler").removeClass("handler_bg").addClass("handler_ok_bg");
                        $(".drag_text").css("color","#fff").html("验证成功");
                        $(document).off("mousemove");
                        $(document).off("mouseup");
                        $(".handler").off("mousedown");
                        e.preventDefault();
                    }
                });
                $(document).on("mouseup",function(e){
                    $(document).off("mousemove");
                    $(document).off("mouseup");
                    var x = e.clientX - $("#drag").offset().left - disX; 
                    if(x < maxWidth){
                        $(".handler").css("left",0);
                        $(".drag_bg").width(0);
                    }
                });
                e.preventDefault();
            });
        });
    </script>

 

posted @ 2018-04-28 15:37  莫尘y  阅读(346)  评论(0编辑  收藏  举报