js-實現常見的拖拽效果(表單滑塊驗證)


本文將詳細介紹拖拽的實現過程,會使用到js的三個事件(鼠標按下mousedown、鼠標移動mousemove、鼠標抬起mouseup),利用這三個事件即可完成拖拽效果。

在沒有拖拽到最右端的情況下,會自動返回,效果圖如下:

具體實現代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 300px;
            height: 30px;
            margin: 40px auto;
            border: 1px #eee solid;
            position: relative;
        }
        p{
            padding: 0;
            margin: 0;
            float: left;
            height: 30px;
            background: yellow;
        }
        span{
            float: left;
            width: 30px;
            height: 30px;
            text-align: center;
            line-height: 30px;
            background-color: violet;
            position: absolute;
            cursor: pointer;;
        }
    </style>
</head>
<body>
    <div>
        <p></p><span>>></span>
    </div>
</body>
<script src="../move.js"></script>
<script>
    class tz{
        constructor(){
            this.div = document.querySelector('div');
            this.p = document.querySelector('p');
            this.span = document.querySelector('span');
            this.init();
        }
        init(){
            // 鼠標按下記錄坐標
            this.span.onmousedown = (eve)=>{
                var e = eve || window.event;
                this.left = e.offsetX;
                // 鼠標按下之后執行后面的鼠標移動和鼠標抬起
                this.move();
                this.up();
            }
        }
        // 鼠標移動事件
        move(){
            var that = this;
            document.onmousemove = function(eve){
                var e = eve || window.event;                
                that.l = e.pageX- that.div.offsetLeft - that.left;
                if(that.l<0){that.l=0};
                if(that.l > that.div.offsetWidth - that.span.offsetWidth){
                    that.l = that.div.offsetWidth - that.span.offsetWidth;
                    that.span.innerHTML = '√';
                }
                that.span.style.left = that.l + 'px';
                that.p.style.width = that.l + 'px';
                return false;
            }
        }
        // 鼠標抬起事件
        up(){
            document.onmouseup = ()=>{
                document.onmousemove=null;
                document.onmouseup = null;
                if(this.l< this.div.offsetWidth - this.span.offsetWidth){
                    move(this.span,{left:0});
                    move(this.p,{width:0});
                }
            }
        }
    }
    new tz();
</script>
</html>
 
 
如果有什么疑問,請在評論區留言


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM