拖動窗口並移動窗口位置

圖片描述

該功能常見於滑動驗證碼
圖片描述javascript

HTML部分css

<div id="box">
    <div id="title">按住拖動</div>
</div>

css部分java

<style>
    * {
        padding: 0;
        margin: 0;
    }
    #box {
        width: 400px;
        height: 300px;
        background-color: orange;
        position: absolute;
        text-align: center;
        color: #ffffff;
    }
    #title {
        width: 100%;
        height: 2em;
        line-height: 2em;
        background-color: #999999;
        cursor: move;
    }
</style>

JS部分瀏覽器

<script type="text/javascript">        
        var box = document.getElementsByClassName('box')[0];        
        var title = document.getElementsByClassName('title')[0];        
        //0.聲明一個開關變量        
        var off = 0;        
        //0.1聲明一個變量一保存鼠標與盒子之間的距離        
        var cur = {};        
        //1.給標題添加鼠標按下事件        
        title.onmousedown = function(e){                            
            off = 1;
            //1.1 計算鼠標位置-盒子到頁面的位置,獲得一個差,永遠不變
            cur.x = e.clientX-box.offsetLeft;
            cur.y = e.clientY-box.offsetTop;            
        }        
        //2.添加鼠標移動事件        
        document.onmousemove = function(e){            
            //2.1判斷按下的開關狀態  若是是真再運行            
            if(!off) return;
            var left = e.clientX - cur.x;            
            var tops = e.clientY - cur.y;
            //限制box不超出瀏覽器
            left = left<0?0:left;
            tops = tops<0?0:tops;
            left = left >= window.innerWidth-400 ? window.innerWidth-400 : left;
            tops = tops >= window.innerHeight-300 ? window.innerHeight-300 : tops;
            
            box.style.left = left+'px';
            box.style.top = tops+'px';            
        }        
        //3.添加鼠標擡起事件
        title.onmouseup = title.onmouseout= function(){            
            console.log('鼠標擡起');            
            off = 0;            
        }            
    </script>
相關文章
相關標籤/搜索