1. 程式人生 > >event滑鼠拖拽(彈框移動)

event滑鼠拖拽(彈框移動)

滑鼠拖拽效果很常見,例如百度的登入頁,點選登入會彈出一個視窗,並且這個視窗可以拖動;首先,要涉及到滑鼠的三個事件,分別為滑鼠按下、移動、鬆開;onmousedown onmousemove onmouseup

下面是程式碼

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>JS滑鼠拖拽</title>
    <style type="text/css">
        * {
            margin: 0px;
            padding: 0px;
        }

        .mask {
            width: 100%;
            height: 4000px;
            position: relative;
            left: 0px;
            top: 0px;
            position: fixed;
            background-color: #000;
            opacity: 0.5;
            fill-opacity: 50;
            display: none;
        }

        .mov {
            position: fixed;
            left: 50%;
            margin-left: -200px;
            width: 400px;
            height: 300px;
            background-color: #fff;
            top: 50%;
            margin-top: -150px;
            display: none;
        }

        .title {
            cursor: move;  
            width: 400px;
            height: 50px;
            background-color: #ccc;
        }
    </style>

</head>

<body>
    <div id="mask" class="mask">

    </div>
    <div id="mov" class="mov">
        <div class="title" id="title" onmousedown="start()" onmouseup="stop()" onmouseout="stop()" onmousemove="zzz()"></div>
    </div>
    <input type="button" value="登入" onclick="show()" />
</body>
<script type="text/javascript">
    var neng = 0;
    function show() {
        document.getElementById("mask").style.display = "block"
        document.getElementById("mov").style.display = "block"
    }
    function zzz() {
        if (neng == 1) {
            var a = window.event || kk;   //IE谷歌 或 谷歌火狐
            var heng = a.clientX
            var zong = a.clientY

         
            //clientX有極值 200-1149==螢幕寬-寬度的一半
            //clientY極值25-300==螢幕高-高度的一半

            var pingk = document.documentElement.clientWidth;     //屏寬不包括滾動條
            var pingh = document.documentElement.clientHeight; 
            
            if(heng<=200){
                heng=200;
            }else if(heng>=pingk-200){
                heng=pingk-200
            }else{

            }

            if(zong<=25){
                zong=25;
            }else if(zong>=pingh-(300-25)){
                zong=pingh-(300-25)
            }else{

            }
            var s = document.getElementById("mov")
            s.style.left = heng + "px"
            s.style.top = zong +125 + "px"
        }

        
    }
    function start(){
            neng = 1;
        }
        function stop(){
            neng = 0;
        }
</script>

</html>