简单的弹出框拖拽关闭事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>弹出框拖拽关闭事件</title>
    <style>
        *{
            margin:0;padding:0;
        }
        #box{
            width:500px;
            height:250px;
            background:#f2f2f2;
            border:1px #ccc solid;
            border-radius:3px;
            position:absolute;
            left:calc(50% - 250px);
            top:calc(50% - 150px);
        }
        .boxHeader{
            height:45px;
            line-height:45px;
            border-bottom:1px #ccc solid;
        }
        .title{
            padding:0 15px;
            color:#333;
            float:left;
        }
        .close{
            padding:0 15px;
            color:#ccc;
            font-size:20px;
            float:right;
            cursor: pointer;
        }
        .boxCont{
            padding:25px 15px;
            font-size:14px;
            color:#666;
            text-align:center;
        }
    </style>
</head>
<body>
<div id="box">
    <div class="boxHeader">
        <div class="title">标题内容</div>
        <div class="close" id="close">×</div>
    </div>
    <div class="boxCont">
        我是内容我是内容我是内容我是内容我是内容
    </div>
</div>
<script>
    var Close=document.getElementById('close');
    Close.onclick=function(){
      box.style.display='none';
    };

    box.onmousedown=function(e){
        var ev= e||event;
        var l=ev.clientX-box.offsetLeft;
        var t=ev.clientY-box.offsetTop;
        document.onmousemove=function(e){
            var ev = e||event;
            var needLeft=ev.clientX-l;
            var needTop=ev.clientY-t;

            //不超出左边边框
            needLeft<0?needLeft=0:needLeft;

            //不超出上边边框
            needTop<0?needTop=0:needTop;

            //不超出右边边框

            var maxLeft=innerWidth-box.offsetWidth;

            needLeft>maxLeft?needLeft=maxLeft:needLeft;

            //不超出底部边框
            var maxTop=innerHeight-box.offsetHeight;
            needTop>maxTop?needTop=maxTop:needTop;

            box.style.left=needLeft+'px';
            box.style.top=needTop+'px';
        };
        document.onmouseup=function(){
            document.onmousemove=document.onmouseup=null;
        };
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/sunjynyue/article/details/84869848