js拖拽

Posted 狗尾草的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js拖拽相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0035)http://fgm.cc/learn/lesson8/03.html -->
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
<title>窗口拖拽(改变大小/最小化/最大化/还原/关闭)</title>
<style type="text/css">
body,div,h2{margin:0;padding:0;}
body{background:url(img/bg.jpg);font:12px/1.5 \\5fae\\8f6f\\96c5\\9ed1;color:#333;}
#drag{position:absolute;top:100px;left:100px;width:300px;height:160px;background:#e9e9e9;border:1px solid #444;border-radius:5px;box-shadow:0 1px 3px 2px #666;}
#drag .title{position:relative;height:27px;margin:5px;}
#drag .title h2{font-size:14px;height:27px;line-height:24px;border-bottom:1px solid #A1B4B0;}
#drag .title div{position:absolute;height:19px;top:2px;right:0;}
#drag .title a,a.open{float:left;width:21px;height:19px;display:block;margin-left:5px;background:url(img/tool.png) no-repeat;}
a.open{position:absolute;top:10px;left:50%;margin-left:-10px;background-position:0 0;}
a.open:hover{background-position:0 -29px;}
#drag .title a.min{background-position:-29px 0;}
#drag .title a.min:hover{background-position:-29px -29px;}
#drag .title a.max{background-position:-60px 0;}
#drag .title a.max:hover{background-position:-60px -29px;}
#drag .title a.revert{background-position:-149px 0;display:none;}
#drag .title a.revert:hover{background-position:-149px -29px;}
#drag .title a.close{background-position:-89px 0;}
#drag .title a.close:hover{background-position:-89px -29px;}
#drag .content{overflow:auto;margin:0 5px;}
#drag .resizeBR{position:absolute;width:14px;height:14px;right:0;bottom:0;overflow:hidden;cursor:nw-resize;background:url(img/resize.png) no-repeat;}
#drag .resizeL,#drag .resizeT,#drag .resizeR,#drag .resizeB,#drag .resizeLT,#drag .resizeTR,#drag .resizeLB{position:absolute;background:#000;overflow:hidden;opacity:0;filter:alpha(opacity=0);}
#drag .resizeL,#drag .resizeR{top:0;width:5px;height:100%;cursor:w-resize;}
#drag .resizeR{right:0;}
#drag .resizeT,#drag .resizeB{width:100%;height:5px;cursor:n-resize;}
#drag .resizeT{top:0;}
#drag .resizeB{bottom:0;}
#drag .resizeLT,#drag .resizeTR,#drag .resizeLB{width:8px;height:8px;background:#FF0;}
#drag .resizeLT{top:0;left:0;cursor:nw-resize;}
#drag .resizeTR{top:0;right:0;cursor:ne-resize;}
#drag .resizeLB{left:0;bottom:0;cursor:ne-resize;}
</style>
<script type="text/javascript">
/*-------------------------- +
  获取id, class, tagName
+-------------------------- */
var get = {
    byId: function(id) {
        return typeof id === "string" ? document.getElementById(id) : id
    },
    byClass: function(sClass, oParent) {
        var aClass = [];
        var reClass = new RegExp("(^| )" + sClass + "( |$)");
        var aElem = this.byTagName("*", oParent);
        for (var i = 0; i < aElem.length; i++) reClass.test(aElem[i].className) && aClass.push(aElem[i]);
        return aClass
    },
    byTagName: function(elem, obj) {
        return (obj || document).getElementsByTagName(elem)
    }
};
var dragMinWidth = 250;
var dragMinHeight = 124;
/*-------------------------- +
  拖拽函数
+-------------------------- */
function drag(oDrag, handle)
{
    var disX = dixY = 0;
    var oMin = get.byClass("min", oDrag)[0];
    var oMax = get.byClass("max", oDrag)[0];
    var oRevert = get.byClass("revert", oDrag)[0];
    var oClose = get.byClass("close", oDrag)[0];
    handle = handle || oDrag;
    handle.style.cursor = "move";
    handle.onmousedown = function (event)
    {
        var event = event || window.event;
        disX = event.clientX - oDrag.offsetLeft;
        disY = event.clientY - oDrag.offsetTop;
        
        document.onmousemove = function (event)
        {
            var event = event || window.event;
            var iL = event.clientX - disX;
            var iT = event.clientY - disY;
            var maxL = document.documentElement.clientWidth - oDrag.offsetWidth;
            var maxT = document.documentElement.clientHeight - oDrag.offsetHeight;
            
            iL <= 0 && (iL = 0);
            iT <= 0 && (iT = 0);
            iL >= maxL && (iL = maxL);
            iT >= maxT && (iT = maxT);
            
            oDrag.style.left = iL + "px";
            oDrag.style.top = iT + "px";
            
            return false
        };
        
        document.onmouseup = function ()
        {
            document.onmousemove = null;
            document.onmouseup = null;
            this.releaseCapture && this.releaseCapture()
        };
        this.setCapture && this.setCapture();
        return false
    };    
    //最大化按钮
    oMax.onclick = function ()
    {
        oDrag.style.top = oDrag.style.left = 0;
        oDrag.style.width = document.documentElement.clientWidth - 2 + "px";
        oDrag.style.height = document.documentElement.clientHeight - 2 + "px";
        this.style.display = "none";
        oRevert.style.display = "block";
    };
    //还原按钮
    oRevert.onclick = function ()
    {        
        oDrag.style.width = dragMinWidth + "px";
        oDrag.style.height = dragMinHeight + "px";
        oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth) / 2 + "px";
        oDrag.style.top = (document.documentElement.clientHeight - oDrag.offsetHeight) / 2 + "px";
        this.style.display = "none";
        oMax.style.display = "block";
    };
    //最小化按钮
    oMin.onclick = oClose.onclick = function ()
    {
        oDrag.style.display = "none";
        var oA = document.createElement("a");
        oA.className = "open";
        oA.href = "javascript:;";
        oA.title = "还原";
        document.body.appendChild(oA);
        oA.onclick = function ()
        {
            oDrag.style.display = "block";
            document.body.removeChild(this);
            this.onclick = null;
        };
    };
    //阻止冒泡
    oMin.onmousedown = oMax.onmousedown = oClose.onmousedown = function (event)
    {
        this.onfocus = function () {this.blur()};
        (event || window.event).cancelBubble = true    
    };
}
/*-------------------------- +
  改变大小函数
+-------------------------- */
function resize(oParent, handle, isLeft, isTop, lockX, lockY)
{
    handle.onmousedown = function (event)
    {
        var event = event || window.event;
        var disX = event.clientX - handle.offsetLeft;
        var disY = event.clientY - handle.offsetTop;    
        var iParentTop = oParent.offsetTop;
        var iParentLeft = oParent.offsetLeft;
        var iParentWidth = oParent.offsetWidth;
        var iParentHeight = oParent.offsetHeight;
        
        document.onmousemove = function (event)
        {
            var event = event || window.event;
            
            var iL = event.clientX - disX;
            var iT = event.clientY - disY;
            var maxW = document.documentElement.clientWidth - oParent.offsetLeft - 2;
            var maxH = document.documentElement.clientHeight - oParent.offsetTop - 2;            
            var iW = isLeft ? iParentWidth - iL : handle.offsetWidth + iL;
            var iH = isTop ? iParentHeight - iT : handle.offsetHeight + iT;
            
            isLeft && (oParent.style.left = iParentLeft + iL + "px");
            isTop && (oParent.style.top = iParentTop + iT + "px");
            
            iW < dragMinWidth && (iW = dragMinWidth);
            iW > maxW && (iW = maxW);
            lockX || (oParent.style.width = iW + "px");
            
            iH < dragMinHeight && (iH = dragMinHeight);
            iH > maxH && (iH = maxH);
            lockY || (oParent.style.height = iH + "px");
            
            if((isLeft && iW == dragMinWidth) || (isTop && iH == dragMinHeight)) document.onmousemove = null;
            
            return false;    
        };
        document.onmouseup = function ()
        {
            document.onmousemove = null;
            document.onmouseup = null;
        };
        return false;
    }
};
window.onload = window.onresize = function ()
{
    var oDrag = document.getElementById("drag");
    var oTitle = get.byClass("title", oDrag)[0];
    var oL = get.byClass("resizeL", oDrag)[0];
    var oT = get.byClass("resizeT", oDrag)[0];
    var oR = get.byClass("resizeR", oDrag)[0];
    var oB = get.byClass("resizeB", oDrag)[0];
    var oLT = get.byClass("resizeLT", oDrag)[0];
    var oTR = get.byClass("resizeTR", oDrag)[0];
    var oBR = get.byClass("resizeBR", oDrag)[0];
    var oLB = get.byClass("resizeLB", oDrag)[0];
    
    drag(oDrag, oTitle);
    //四角
    resize(oDrag, oLT, true, true, false, false);
    resize(oDrag, oTR, false, true, false, false);
    resize(oDrag, oBR, false, false, false, false);
    resize(oDrag, oLB, true, false, false, false);
    //四边
    resize(oDrag, oL, true, false, false, true);
    resize(oDrag, oT, false, true, true, false);
    resize(oDrag, oR, false, false, false, true);
    resize(oDrag, oB, false, false, true, false);
    
    oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth) / 2 + "px";
    oDrag.style.top = (document.documentElement.clientHeight - oDrag.offsetHeight) / 2 + "px";
}
</script>
</head>
<body>
<div id="drag" style="left: 661px; top: 131px; width: 733px; height: 549px;">
    <div class="title" style="cursor: move;">
        <h2>这是一个可以拖动的窗口</h2>
        <div>
            <a class="min" href="javascript:;" title="最小化"></a>
            <a class="max" href="javascript:;" title="最大化"></a>
            <a class="revert" href="javascript:;" title="还原"></a>
            <a class="close" href="javascript:;" title="关闭"></a>
        </div>
    </div>
    <div class="resizeL"></div>
    <div class="resizeT"></div>
    <div class="resizeR"></div>
    <div class="resizeB"></div>
    <div class="resizeLT"></div>
    <div class="resizeTR"></div>
    <div class="resizeBR"></div>
    <div class="resizeLB"></div>
    <div class="content">
        ① 窗口可以拖动;<br>
        ② 窗口可以通过八个方向改变大小;<br>
        ③ 窗口可以最小化、最大化、还原、关闭;<br>
        ④ 限制窗口最小宽度/高度。
    </div>    
</div>
 
 
</body></html>

  

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0035)http://fgm.cc/learn/lesson6/01.html -->
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
<title>完美拖拽</title>
<style type="text/css">
html,body{overflow:hidden;}
body,div,h2,p{margin:0;padding:0;}
body{color:#fff;background:#000;font:12px/2 Arial;}
p{padding:0 10px;margin-top:10px;}
span{color:#ff0;padding-left:5px;}
#box{position:absolute;width:300px;height:150px;background:#333;border:2px solid #ccc;top:50%;left:50%;margin:-75px 0 0 -150px;}
#box h2{height:25px;cursor:move;background:#222;border-bottom:2px solid #ccc;text-align:right;padding:0 10px;}
#box h2 a{color:#fff;font:12px/25px Arial;text-decoration:none;outline:none;}
</style>
<script type="text/javascript">
window.onload=function(){
    var positionArray = [];
 
    var box = document.getElementById("box");
    box.onmousedown = function(evt){
        positionArray = [];
        var x = evt.offsetX;
        var y = evt.offsetY;
        document.onmousemove = function(evt){
            
            box.style.left = evt.clientX - x + "px";
            box.style.top = evt.clientY - y + "px";
            console.log({left:box.offsetLeft, top: box.offsetTop})
            positionArray.push({left:box.offsetLeft, top: box.offsetTop});
        }
    }
    
    box.onmouseup = function(){
        document.onmousemove = null;
    }
    box.children[0].firstChild.onmousedown = function(evt){
        evt.stopPropagation();
    }
    
    box.children[0].firstChild.onclick = function(){
        
        console.log(positionArray.length);
        var index = positionArray.length-1;
        var timer = setInterval(function(){
            if(index < 0) {
                clearInterval(timer);
                return;
            }
            box.style.left = positionArray[index--].left+"px";
            box.style.top = positionArray[index--].top+"px";
        
        },30);
        
        
    }
};
</script>
</head>
<body>
<div id="box" style="margin-left: 0px; margin-top: 0px; left: 533px; top: 231px;">
    <h2><a href="javascript:;">点击回放拖动轨迹</a></h2>
    <p><strong>Drag:</strong><span>false</span></p>
    <p><strong>offsetTop:</strong><span>231</span></p>
    <p><strong>offsetLeft:</strong><span>533</span></p>
</div>
 
 
</body></html>

  

3.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖拽</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        #box {
            position: absolute;
            width: 100px;
            height: 100px;
            background: red;
            cursor: move;
        }
    </style>
</head>
<body>
    活在自己幻想里的母亲和希冀得到爱的女儿。 ------------------题记
 
厌倦和巨大的悲伤后面,充塞着雾霭沉沉的生存。优雅美丽又自私偏执的法国女人Hanah,同时是母亲,也是摄影家。
然而这样的身份对于女儿Violtte来说就是一场灾难。每个小姑娘,有谁没在小时候偷偷用过妈妈的化妆品,没偷偷穿过妈妈的高跟鞋,
没想象过自己长大的样子?但是我们都幸福的长大了,长成了Hanah眼里的庸俗的凡人。
Hanah则把这些变为现实诸加在了女儿Violtte的身上。开始我甚至会慨叹到底是从事艺术工作的,真是前卫先锋的母亲。
Violtte开始有着的那一点新鲜和兴奋,能和母亲共处一室或者说能帮母亲工作的满足成了整幕悲剧里唯一平和温馨的片段。
梳麻花辫着毛衫的跳房子小姑娘就像洋娃娃一样被母亲一步步摆弄成自己喜欢的样子——穿漂亮的衣服,画精致的妆,拍美美的照片,
见识形形色色的人。但母亲Hanah并不止于此,她想要的越来越多,或哥特或洛可可的萝莉已经不足以吸引眼球,还要更大胆更搏出位的,
女儿身上的衣服变成了通往艺术殿堂的枷锁,艺术与色情在母亲眼里达成了完美的统一。
美有没有边界,如果有,它在哪?母亲得到了自己梦寐以求的,赞美与法郎源源不断。女儿失去了所能失去的,不被同龄人接受,也不能一夕长大。
有多爱就有多恨。Violtte逃回家里反锁了门向奶奶哭诉甚至说是求助——“我再也不要见到她”,
年迈的奶奶是以怎样的心情说“我老了,我又老又累,我不能帮你了”。Violtte只有一个妈妈,但Hanah不止有一个模特。
Violtte不能继续拍下去同时接受不了妈妈有新模特,又不能像电影开头的那样回归安宁的生活。
她就在这个夹缝中苦苦挣扎,在这些矛盾里几近崩溃,她甚至对Hanah大吼“我想死”。
影片末尾,Hanah透露的那些隐秘终于成了压垮骆驼的最后一根稻草——我的血液里流淌着incest的原罪。
所以Hanah 是如此厌恶“父系”,不仅是为自己也是为女儿。 对母亲的失望恨意终于变成了恶心和深刻的悲哀,
Violtte在失去母爱的同时也失去了父爱,唯一的救赎——奶奶早已离世,无法面对这些的Violtte就只能不断的逃避下去,不然还能怎么办?
这样大一个世界,她却连一个夹缝都没有。
也许Hanah是真的爱Violtte,如此悲伤,又如此沉重。——也许你我终将行踪不明,但是你该知道我曾经为你动情
 
 
    <div id="box"></div>
    <script>
        var oBox = document.getElementById(\'box\');
        var maxLeft = document.documentElement.clientWidth - oBox.offsetWidth;
        var maxTop = document.documentElement.clientHeight - oBox.offsetHeight;
        oBox.onmousedown = function (ev) {
            var e = ev || window.event;
            // 记录鼠标相对于box左侧和上侧的偏移距离
            var iX = e.clientX - oBox.offsetLeft;
            var iY = e.clientY - oBox.offsetTop;
 
            // 创建一个透明层
            if(oBox.setCapture) {
                oBox.setCapture();
            }
            // 鼠标移动
            document.onmousemove = function (ev) {
                var e = ev || window.event;
 
                // 计算移动后的距离
                var iL = e.clientX - iX;
                var iT = e.clientY - iY;
 
                // 限定左侧
                if(iL < 0) {
                    iL = 0;
                }
 
                // 限定上侧
                if(iT < 0) {
                    iT = 0;
                }
 
                // 限定右侧
                if(iL > maxLeft) {
                    iL = maxLeft;
                }
                // 限定下侧
                if(iT > maxTop) {
                    iT = maxTop;
                }
                oBox.style.left = iL + \'px\';
                oBox.style.top  = iT + \'px\';
            }
            // 鼠标松开
            document.onmouseup = function () {
                // 取消mousemove事件
                document.onmousemove = null;
                // 取消up事件
                document.onmouseup = null;
 
                // 释放透明层(捕获)
                if(oBox.releaseCapture) {
                    oBox.releaseCapture();
                }
            }
            // 阻止浏览器的默认行为
            return false;
        }
    </script>
</body>
</html>

  

4.九宫格拖拽
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>九宫格拖拽</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        #box {
            position: relative;
            list-style: none;
            margin: 30px auto;
            width: 400px;
            height: 400px;
            border: 1px solid #ccc;
        }
        #box li {
            position: absolute;
            width: 120px;
            line-height: 120px;
            background: #eee;
            font-size: 50px;
            text-align: center;
        }
        #box .active {
            z-index: 1;
            color: #fff;
            background: blue;
        }
    </style>
</head>
<body>
    <ul id="box">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
    </ul>
    <script>
        
        var oBox = document.getElementById(\'box\');
        var aLi = oBox.children;
 
        for(var i = 0; i < aLi.length; i++) {
            // 第1LI:left: 10 + 0 * 130 top: 10 + 0 * 130
            // 第2LI:left: 10 + 1 * 130 top: 10 + 0 * 130
            // 第3LI:left: 10 + 2 * 130 top: 10 + 0 * 130
            // 第4LI:left: 10 + 0 * 130 top: 10 + 1 * 130
            // 第5LI:left: 10 + 1 * 130 top: 10 + 1 * 130
            // 第6LI:left: 10 + 2 * 130 top: 10 + 1 * 130
            // 第7LI:left: 10 + 0 * 130 top: 10 + 2 * 130
            // 第8LI:left: 10 + 1 * 130 top: 10 + 2 * 130
            // 第9LI:left: 10 + 2 * 130 top: 10 + 2 * 130
 
            // 布局
            aLi[i].style.left = 10 + (i % 3) * 130 + \'px\';
            aLi[i].style.top = 10 + Math.floor(i / 3) * 130 + \'px\';
 
            // 记录顺序
            aLi[i].index = i;
 
            // 拖拽
            aLi[i].onmousedown = function (ev) {
                var e = ev || window.event;
 
                var iX = e.clientX - this.offsetLeft;
                var iY = e.clientY - this.offsetTop;
                // 针对低版本的IE,建立透明层
                if(this.setCapture) {
                    this.setCapture();
                }
                // 添加样式
                this.className = \'active\';
                var that = this;
                document.onmousemove = function (ev) {
                    var e = ev || window.event;
 
                    var iL = e.clientX - iX;
                    var iT = e.clientY - iY;
 
                    that.style.left = iL + \'px\';
                    that.style.top  = iT + \'px\';
 
                    // 判断是否发生交换位置
                    for(var j = 0; j < aLi.length; j++) {
                        if(
                               aLi[j] !== that // 排除自身
                            && that.offsetLeft + that.offsetWidth > aLi[j].offsetLeft + aLi[j].offsetWidth / 2
                            && that.offsetTop + that.offsetHeight > aLi[j].offsetTop + aLi[j].offsetHeight / 2
                            && that.offsetLeft < aLi[j].offsetLeft + aLi[j].offsetWidth / 2
                            && that.offsetTop < aLi[j].offsetTop + aLi[j].offsetHeight / 2
                        ) {
                            // 交换顺序
                            var temp = aLi[j].index;
                            aLi[j].index = that.index;
                            that.index = temp;
 
                            // 交换位置
                            aLi[j].style.left = 10 + (aLi[j].index % 3) * 130 + \'px\';
                            aLi[j].style.top  = 10 + Math.floor(aLi[j].index / 3) * 130 + \'px\';
                            break;
                        }
                    }
                };
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup   = null;
                    // 针对低版本的IE,释放透明层
                    if(this.releaseCapture) {
                        this.releaseCapture();
                    }
                    // 去掉样式
                    that.className = \'\';
 
                    // 还原位置
                    that.style.left = 10 + (that.index % 3) * 130 + \'px\';
                    that.style.top  = 10 + Math.floor(that.index / 3) * 130 + \'px\';
                };
                // 阻止浏览器的默认行为
                return false;
            }
        }
 
    </script>
</body>
</html>

  

 
 
 

以上是关于js拖拽的主要内容,如果未能解决你的问题,请参考以下文章

js拖拽问题,求大神详解

原生JS实现图标图片拖拽

纯js实现DIV拖拽

vuejs2.0使用Sortable.js实现的拖拽功能( 转)

JS拖拽效果的原理及实现

拖拽系列利用JS面向对象OOP思想实现拖拽封装