JS实现拖拽小案例

Posted Scar007

tags:

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单的拖拽</title>
    <link rel="stylesheet" href="../toolkit/reset.min.css">
    <style>
        #box{
            height: 200px;
            width: 200px;
            background-color: #e277ff;
            position: absolute;
            cursor: move;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    var box=document.getElementById("box");
    function drag(e) {
        e=e||window.event;
        var _this=this;
        var mouseX=e.clientX,
                mouseY=e.clientY,
                boxL=this.offsetLeft,
                boxT=this.offsetTop;
        document.onmousemove=function (e) {
            e=e||window.event;
            var curMouseX=e.clientX,
                    curMouseY=e.clientY,
                    curBoxL=curMouseX-mouseX+boxL,
                    curBoxT=curMouseY-mouseY+boxT;

            var minW=0,maxW=((document.documentElement.clientWidth||document.body.clientWidth)-_this.offsetWidth);
            var minH=0,maxH=((document.documentElement.clientHeight||document.body.clientHeight)-_this.offsetHeight);
            if(curBoxL<=minW){
                curBoxL=minW;
            }else if(curBoxL>=maxW){
                curBoxL=maxW
            }
            if(curBoxT<=minH){
                curBoxT=minH;
            }else if(curBoxT>=maxH){
                curBoxT=maxH;
            }

            _this.style.left=curBoxL+"px";
            _this.style.top=curBoxT+"px";
        };
        document.onmouseup=function () {
            document.onmousemove=null;
        }
    }
    box.onmousedown=drag;
</script>
</body>
</html>

 

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

JS——事件详情(拖拽案例:onmousedownonmousemoveonmouseup方法)

cookie结合js 实现记住的拖拽

前端实操案例丨如何实现JS向Vue传值

js拖拽效果的原理及实现

js完美拖拽封装及其案例

JS之拖拽案例