简单的拖拽窗口实现

时间:2022-01-23 20:02:54
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>拖拽窗口</title>
    <style> *{margin: 0px;padding: 0px;} html {width: 100%;height: 100%;} body{width: 100%;height: 100%;background-color: #eeeeee;overflow: hidden;} .twindow{width: 300px;height: 200px;border: 0px solid #aaaaaa;background-color: #ffffff;opacity: 1;position: absolute;left: 50px;top:50px;} .tbody{ width: 300px;height: 150px;border: 0px solid #aaaaaa; } .thead{ width: 100%;height: 25px;border: 0px solid #aaaaaa;background-color: #999999; } .thead:hover { cursor:move; } .tdiv{ width: 100%;height: 100%;position: relative; } </style>
</head>
<body onselectstart="return false;">

<div id="twindow" class="twindow">
        <div id="tdiv" class="tdiv">
        <div id="thead" class="thead">
            拖拽窗口
        </div>
            <div id="tbody" class="tbody">
            内容
        </div>
    </div>
</div>

</body>
<script type="text/javascript"> function newWindow(){ this.id= function (id) { return document.getElementById(id) }; this.move= function (type,div0,div2,callback) { div2.onmousedown= function (e0) { var e = e0 ||event; var x=e.clientX-div0.offsetLeft; var y=e.clientY-div0.offsetTop; document.onmousemove = function(e1){ var l=(e1.clientX-x),t=(e1.clientY-y); var b=document.body.offsetWidth-parseInt(div2.offsetWidth); if(type==0){ var c=document.body.offsetHeight-parseInt(div2.offsetHeight);//可以拖动到下方隐藏窗口内容,只保留头部拖动条 }else if(type==1){ var c=document.body.offsetHeight-parseInt(div2.offsetHeight)-div2.parentNode.getElementsByTagName('div')[1].offsetHeight;//整个窗口显示,包括内容窗口 } div0.style.left=(l>0&&l<b?l:l<0?0:l>b?b:'')+'px'; div0.style.top=(t>0&&t<c?t:t<0?0:t>c?c:'')+'px'; }; document.onmouseup = function(){ document.onmousemove =null; document.onmouseup = null; callback(); }; return false; }; }; this.moveWindow= function (json) { //id1是整个要拖动的窗口, //id2是触发拖动事件的head this.move(json.type,this.id(json.window),this.id(json.head),json.callback); }; } var nWin=new newWindow(); nWin.moveWindow({ type:0, //type=0,可以拖动到下方隐藏窗口内容,只保留头部拖动条.//type=1,整个窗口显示,包括内容窗口 window:'twindow',//整个窗口 head:'thead',//拖动的头部 callback: function () { //鼠标拖拽结束释放后触发的事件 console.log(Date.now()); } }); </script>
</html>