弹出层移动效果

140 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .body {
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            position: fixed;
            left: 0;
            top: 0;
        }

        .container {
            width: 300px;
            height: 400px;
            background: #fff;
            position: absolute;
            border: 2px solid #eee;

        }

        .title {
            height: 40px;
            background: #eee;
            user-select: none;
            cursor: move;
            text-indent: 1em;
            line-height: 40px;
        }
    </style>
</head>

<body>
    <div class="body">
        <div class="container">
            <div class="title">
                登录
            </div>
        </div>
    </div>

</body>
<script>
    //需要根据鼠标的触发状态判断是否触发,所以建立了canmove
    let canmove = false
    let offsetX = 0, offsetY = 0
    //事件源:获取页面中的元素
    let demo = document.getElementsByClassName('container')[0]
    let title = document.getElementsByClassName('title')[0]
    //鼠标按下触发
    title.onmousedown = (e) => {
        canmove = true
        //获得鼠标在该div中的位置
        offsetX = e.pageX - demo.offsetLeft
        offsetY = e.pageY - demo.offsetTop
    }
    //鼠标弹起触发
    window.onmouseup = () => {
        canmove = false
    }
    //失去焦点时触发
    window.blur = () => {
        canmove = false
    }
    //鼠标移动触发
    window.onmousemove = (e) => {
        if (canmove) {
            //根据鼠标的位置得出div距离父元素左边和右边的距离
            let x = e.pageX - offsetX
            let y = e.pageY - offsetY
            let xMax = window.innerWidth - demo.offsetWidth
            let yMax = window.innerHeight - demo.offsetHeight
            //此判断是为了防止将div移除window
            if (x < 0) x = 0
            if (y < 0) y = 0
            if (x > xMax) x = xMax
            if (y > yMax) y = yMax
            demo.style.left = x + 'px'
            demo.style.top = y + 'px'
        }

    }


</script>

</html>