JS实现拖动模态框效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            padding: 0;
            margin: 0;
        }

        .box {
            display: none;
            width: 400px;
            height: 300px;
            text-align: center;
            border: 1px solid #cccccc;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            z-index: 2;
            background-color: #ffffff;
        }

        .form {
            line-height: 50px;
        }

        .close {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            position: absolute;
            right: -30px;
            top: -30px;
            line-height: 60px;
            text-align: center;
            background-color: #ffffff;
        }

        .logbg {
            display: none;
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .title {
            height: 50px;
            line-height: 50px;
            cursor: move;
        }
    </style>
</head>
<body>
<button class="open">点击,弹出登录框</button>
<div class="box">
    <div style="position: relative">
        <div class="title">登录会员</div>
        <div class="form">
            用户名<input typeof="text">
        </div>
        <div class="form">
            登录密码<input typeof="text">
        </div>
        <button>登录会员</button>
        <a href="javascript:;" class="close">关闭</a>
    </div>
</div>
<div class="logbg"></div>
<script>
    var box = document.querySelector('.box');
    var title = document.querySelector('.title');
    var open = document.querySelector('.open');
    var logbg = document.querySelector('.logbg');
    open.addEventListener('click', function () {
        box.style.display = 'block';
        logbg.style.display = 'block';
    })
    title.addEventListener('mousedown', function (e) {
        console.log(e)
        var left = e.pageX - box.offsetLeft;
        var top = e.pageY - box.offsetTop;

        function move(e) {
            box.style.left = e.pageX - left + 'px';
            box.style.top = e.pageY - top + 'px';
        }

        document.addEventListener('mousemove', move);
        document.addEventListener('mouseup', function (e) {
            document.removeEventListener('mousemove', move)
        })
    })
</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值