js写一个页面元素拖动效果,如何判断鼠标在点击后发生了拖动?

在拖动目标元素的时候,首先触发了mousedown事件,然后再触发mousemove事件,那么如何判断它触发了呢?是直接

document.onmousemove=function(){
    test=1;//修改状态
}

然后判断test值来触发mousemove事件?可是我总觉得这样子不太优雅,我想问一下有类似经验的大神,你们是如何处理这里的鼠标状态的判断的?

阅读 7.4k
6 个回答

<!DOCTYPE html>
<html>
<head lang="en">

<meta charset="UTF-8">  
<title></title>  
<style type="text/css">  
    #xixi {  
        width:200px; height: 200px; position:absolute;  
        left: 50px; top: 50px; background-color: lightcyan;  
    }  
    #haha {  
        position:absolute; left:300px; top:300px;  
        background-color: yellow; width:200px; height: 200px;  
    }  

</style>  
<script type="text/javascript" src="js/mylib.js"></script>  
<script type="text/javascript">  
    window.onload = function() {  
        var obj1 = createDraggableObject();  
        var obj2 = createDraggableObject();  
        obj1.init($('xixi'));  
        obj2.init($('haha'));  
    };  
</script>  

</head>
<body>

<div id="xixi">Fuck!</div>  
<div id="haha">Shit!</div>  

</body>
</html>

/** 
  • 根据id获取页面元素

  • @param id

  • @returns {HTMLElement}
    */

function $(id) {

return document.getElementById(id);  

}

/**

  • 创建可拖拽对象的工厂方法
    */

function createDraggableObject() {

return {  
    obj: null, left: 0, top: 0,  
    oldX: 0, oldY: 0, isMouseLeftButtonDown: false,  
    init: function (obj) {  
        this.obj = obj;  
        var that = this;  
        this.obj.onmousedown = function (args) {  
            var evt = args || event;  
            this.style.zIndex = 100;  
            that.isMouseLeftButtonDown = true;  
            that.oldX = evt.clientX;  
            that.oldY = evt.clientY;  
            if (this.currentStyle) {  
                that.left = parseInt(this.currentStyle.left);  
                that.top = parseInt(this.currentStyle.top);  
            }  
            else {  
                var divStyle = document.defaultView.getComputedStyle(this, null);  
                that.left = parseInt(divStyle.left);  
                that.top = parseInt(divStyle.top);  
            }  
        };  
        this.obj.onmousemove = function (args) {  
            that.move(args || event);  
        };  
        this.obj.onmouseup = function () {  
            that.isMouseLeftButtonDown = false;  
            this.style.zIndex = 0;  
        };  
    },  
    move: function (evt) {  
        if (this.isMouseLeftButtonDown) {  
            var dx = parseInt(evt.clientX - this.oldX);  
            var dy = parseInt(evt.clientY - this.oldY);  
            this.obj.style.left = (this.left + dx) + 'px';  
            this.obj.style.top = (this.top + dy) + 'px';  
        }  
    }  
};  

}

百度的

我记得我大半个月前回答另一个问题的时候还写过一个demo

传送门

然后,点击看demo的代码和效果
http://jsfiddle.net/7ra1tgct/1/

楼上说的ondrag确实不错,值得推荐,但有时如果要考虑兼容性就不行了哦

把mousemove 函数mouseup函数写在mousedown里面,这样自由鼠标按下后才能触发nousemove,也能检测鼠标抬起

onmousedown之后,给body添加mousemove事件,然后根据坐标调整移动的元素,指定元素mouseup之后,删除body的mousemove事件,这是我之前写的时候的思路

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        #drag{
            position: absolute;
            left: 0;
            top: 0;
            width: 100px;
            height: 100px;
            background: #56718A;
            cursor:pointer;
        }
    </style>
</head>
<body>
    <div id="drag"></div>
    <script>
        window.onload=function(){
            var obj=document.getElementById("drag");
            var x=0;
            var y=0;
            var hasMove=0;
            var hasDown=0;
            function setprice(x,y){
                if(x>=50&&y>=50){
                    obj.style.left=(x-50)+"px";
                    obj.style.top=(y-50)+"px";
                }else if(x>=50&&y<50){
                    obj.style.left=(x-50)+"px";
                    obj.style.top=y+"px";
                }else if(x<50&&y>=50){
                    obj.style.left=x+"px";
                    obj.style.top=(y-50)+"px";
                }else{
                    obj.style.left=x+"px";
                    obj.style.top=y+"px";
                }
            }
            function mousedown(){
                hasMove=0;
                hasDown=1;
                x=event.clientX;
                y=event.clientY;
                setprice(x,y);
                document.addEventListener("mousemove",mousemove);
                document.addEventListener("mouseup",mouseup);
            }
            function mousemove(){
                hasMove=1;
                if(hasDown==1){
                    x=event.clientX;
                    y=event.clientY;
                    setprice(x,y);
                    document.addEventListener("mouseup",mouseup);
                }else{
                    document.removeEventListener("mousemove",mousemove);
                }
                
            }
            function mouseup(){
                hasMove=1;
                hasDown=0;
                x=event.clientX;
                y=event.clientY;
                setprice(x,y);
                document.removeEventListener("mousemove",mousemove);
                document.removeEventListener("mouseup",mouseup);
            }
            obj.onmousedown=function(){
                mousedown();
            }
            
        }
    </script>
</body>

</html>

新手上路,请多包涵
<html>  
<head>  
    <meta charset="utf-8" />  
    <title></title>  
    <style>*{margin: 0;padding: 0;}</style>  
</head>  
<body>  
<div id="demo" style="position:absolute;width: 100px;height: 100px;background: #ccc;border:solid 1px #ccc;">
    <div id="demoheader" style="border-bottom: 1px dotted #fff;margin-bottom: 10px">头部</div>
    <div>头部拖拽</div>
    
</div>  

<div id="demo2" style="position:absolute; left: 50% ;top: 50%; width: 100px;height: 100px;background: #ccc;border:solid 1px #ccc;">
    <div style="border-bottom: 1px dotted #fff;margin-bottom: 10px">头部2</div>
    <div>内容2</div>
    <button id="demoheader2"  >点我拖拽</button>
</div>
<div id="demoheader3" style="position:absolute;right:20px;bottom:20px;width: 100px;height: 100px;background: #ccc;border:solid 1px #ccc;">
    <div style="border-bottom: 1px dotted #fff;margin-bottom: 10px">头部3</div>
    <div>整体拖拽</div>
</div>
</body>  
<script>  

/*
    dragId:触发拖拽的元素ID,如面板的头部;
    targetId:可选,拖拽的元素的ID,如整个面板,如果不指定,则未拖拽触发元素本身
*/
var dragElement = function(dragId, targetId) {
  var dragEle = document.getElementById(dragId),
      targetEle = targetId == undefined ? dragEle: document.getElementById(targetId)
  //用于确定是否是拖拽的对象  
  var drag;
  //鼠标位于目标元素上的时候距离目标元素的位置  
  var x, y;
  
  //鼠标按下去
  dragEle.onmousedown = function(evt) {
    //取得事件对象  
    _event = evt || window.event;
    //设置drag元素  
    target = _event.target || _event.srcElement;
    x = _event.clientX - targetEle.offsetLeft;
    y = _event.clientY - targetEle.offsetTop;
    drag = targetEle;

    /*确保鼠标移动和鼠标松开是放在dragEle.onmousedown里的,否则与onmousedown平级只能启用最后一次调用
    另外,通过将onmousemove和onmouseup绑定到document上启用拖拽,而不是绑定到dragEle上,避免鼠标滑动太快导致拖拽卡顿
    */
    //鼠标移动  
    document.onmousemove = function(evt) {
      //确定鼠标是在目标元素上按下去后才开始移动  
      if (drag) {
      
        _event = evt || window.event;
        
        //设置边界  
        var left = _event.clientX - x;
        var top = _event.clientY - y;
        body = document.documentElement || document.body;

        if (left < 0) left = 0;
        if (left > body.offsetWidth - drag.offsetWidth) left = body.offsetWidth - drag.offsetWidth;
        
        if (top < 0) top = 0;
        if (top > (body.offsetHeight - drag.offsetHeight)) top = (body.offsetHeight - drag.offsetHeight);
        

        //设置样式  
        drag.style.cursor = 'move';
        drag.style.border = 'dashed 1px red';
        drag.style.left = left + 'px';
        drag.style.top = top + 'px';
      }
    }

    //松开鼠标  
    document.onmouseup = function(evt) {
      if (drag) {
        //卸载样式  
        drag.style.cursor = '';
        drag.style.border = 'dashed 1px #ccc';
      }
      drag = null;
    }
  }
}

    
    dragElement("demoheader", "demo");
    dragElement("demoheader2", "demo2");
    dragElement("demoheader3");
    
    
</script>  
</html>  
推荐问题