js鼠标拖动div

Posted

tags:

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#overwidth: 100px;height: 30px;background: red;position: absolute;left: 20px;top: 500px;
</style>
</head>
<body>
<div id="over" onmousedown="down(this,event)" onmousemove="move(this,event)" onmouseup="seup(this,event)">

</div>
<script type="text/javascript">
var posX,posY;
var downX,downY;
var mark=false;
function down(obj,event)

obj.style.cursor="move";
posX=obj.style.left;
posY=obj.style.top;
downX=event.clientX;
downY=event.clientY;
mark=true;

function move(obj,event)

var moveX=event.clientX;
var moveY=event.clientY;
if (mark)
obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX) + "px";
obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px";


function seup(obj,event)

if (mark)
var moveX=event.clientX;
var moveY=event.clientY;
obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX)+ "px";
obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px";
downX=moveX;
downY=moveY;

obj.style.cursor="default";
mark = false;

</script>
</body>
</html> 我的代码不能实现拖动,就改变了鼠标的样式;请问错在哪里?研究好长时间都没有明白

你的obj.style.left是获取不到的因为该div没有设置style属性所以只要将样式改为行内就行了
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文哥讨厌IE</title>
</head>
<body>
    <div id="over" onmousedown="down(this,event)" style="width:100px;height:30px;background:red;position:absolute;left:20px;top:500px;" onmousemove="move(this,event)" onmouseup="seup(this,event)">
        
    </div>
<script type="text/javascript">
    var posX,posY;
    var downX,downY;
    var mark=false;
    function down(obj,event)
    
        obj.style.cursor="move";
        posX=obj.style.left;
        posY=obj.style.top;
        downX=event.clientX;
        downY=event.clientY;
        mark=true;
        ///alert(posX);
        ///alert(posY);
    
    function move(obj,event)
    
        var moveX=event.clientX;
        var moveY=event.clientY;
        if (mark) 
            obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX) + "px";
            obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px";
        
    
    function seup(obj,event)
    
        if (mark) 
            var moveX=event.clientX;
            var moveY=event.clientY;
            obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX)+ "px";
            obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px";
            downX=moveX;
            downY=moveY;
        
        obj.style.cursor="default";
            mark = false; 
    
</script>
</body>
</html>

参考技术A <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>

</head>
<body>
<div id="box1" style = 'width:100px; height: 100px; background:#ccc; position:fixed;'></div>
<!-- 注意 盒子一定要定位 position:fixed; 或者 position:absolute;-->
</body>
<script type="text/javascript">
function getPos(e)//这是一个 获取鼠标位置的函数
var oEvent = e || event;
return x: oEvent.clientX + document.documentElement.scrollLeft || document.body.scrollLeft,
y: oEvent.clientY +document.documentElement.scrollTop || document.body.scrollTop;


document.getElementById('box1').onmousedown = function(e) //你要拖动对象在mousedown的时候发生的事情
var oEvent = e || event;
var pos = getPos(oEvent);
var _this = this;
_this.style.cursor = 'move';//改变鼠标状态
_this.disY = pos.y - _this.offsetTop;
_this.disX = pos.x - _this.offsetLeft;
document.onmousemove =function(e) //在鼠标按下的时候 并且 移动的时候 发生的事情
var oEvent = e || event;
var dpos = getPos(oEvent);
var t = dpos.y-_this.disY ; //移动的时候获取的 移动 top值
var l = dpos.x-_this.disX ;//移动的时候获取的 移动 left

_this.style.top=t + "px"; //这两条给盒子赋值
_this.style.left=l + "px";
;
document.onmouseup = function()//鼠标弹起的时候做的事情 一些释放 操作
_this.style.cursor = 'pointer'
this.onmousemove = null;
this.onmouseup = null;
try
_this.releaseCapture();catch(e)
;
try
_this.setCapture();catch(b) //这里是为了 让盒子拖动的时候不要复制页面里面的其他内容
return false;

;
</script>
</html>

这是我写的代码 你参照一下追问

这类代码网上一大堆,随便找得到,但是我想知道的是我错在哪里,帮忙分析下我的代码,看问题出在哪里

追答

你的变量定义有问题, 到了别的函数里面会变成 NaN, 把变量设置好了

鼠标拖动改变DIV等网页元素的大小的最佳实践

1.初次实现

1.1 html代码

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>div change width by drag</title>
        <script src="../jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
    </head>

    <body>
        <h1>div change width by drag</h1>
        <div id="pos" style="color:red"></div>
        
        <div id="myDiv" style="border:2px solid red;width:300px;height:50px;margin-left: 100px;margin-top: 20px"></div>
    </body>
</html>

1.2 js代码

          var eleLeft = $(\'#myDiv\').offset().left;
                var isMouseDown = false;
                var borderLen = 4; //左右边框
                
                $(\'#myDiv\').bind({
                    mousedown:function(e){
                        var ele = $(this);
                        var rightPos = eleLeft + ele.width() + borderLen;
                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            isMouseDown = true;

                        }
                    },
            
                    mousemove:function(e){
                        var ele =  $(this);
                        var rightPos = eleLeft + ele.width() + borderLen;
                        $(\'#pos\').text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+rightPos);

                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            ele.css(\'cursor\',\'e-resize\');
                        }else{
                            if(!isMouseDown){
                                ele.css(\'cursor\',\'auto\');
                            }
                        }
                        if(isMouseDown){
                            ele.width((e.pageX-eleLeft-borderLen)+\'px\');  //新鼠标位置-div距左-borderLen
                        }
                    },
                    mouseup:function(e){
                        isMouseDown = false;
                    }
                });

1.3 结果

只能往左拖动使div宽度变小,往右拖动没有用!原因往右拖动鼠标mousemove事件无法被div捕获了。拖动时也很难停下来!所以得改进。

 

2.再次改进

          $(\'#myDiv\').bind({
                    mousedown:function(e){
                        var ele = $(this);
                        var rightPos = eleLeft + ele.width() + borderLen;
                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            isMouseDown = true;
                        }
                    }
                });

                $(\'body\').bind({
                    mousemove:function(e){
                        var ele = $(\'#myDiv\');
                        var rightPos = eleLeft + ele.width() + borderLen;
                        $(\'#pos\').text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+rightPos);

                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            ele.css(\'cursor\',\'e-resize\');
                        }else{
                            if(!isMouseDown){
                                ele.css(\'cursor\',\'auto\');
                            }
                        }
                        if(isMouseDown){
                            ele.width((e.pageX-eleLeft-borderLen)+\'px\');  
                        }
                    },
                    mouseup:function(e){
                        isMouseDown = false;
                    }
                });

 这次解决了上述问题,可以往右拖,并且随时可以停下来了。到这里就完成了吗?NO!

当我引入一个其他div,并且阻止mouseup事件冒泡情况怎么样呢?答案是,拖动到这个其它div上放开鼠标后无法停止下来!

<div id="otherDiv" style="border: 2px solid blue;width: 200px;height: 200px;margin-left: 400px"></div>

 

         $(\'#otherDiv\').mouseup(function(e){
                    //e.preventDefault(); //阻止默认行为
                    e.stopPropagation(); //阻止事件冒泡(导致body捕获不到mouseup事件)
                });

 

3.完美解决

拖动停止可能受到其它元素的干扰,怎么解决?想到一些弹出层点击其它其它地方隐藏的功能,让我想到了,加一个遮罩层,让mouseup事件总是可以响应,不就搞定了嘛!

        $(\'#myDiv\').bind({
                    mousedown:function(e){
                        var ele = $(this);
                        var rightPos = eleLeft + ele.width() + borderLen;
                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            isMouseDown = true;

                            //创建遮罩层,防止mouseup事件被其它元素阻止冒泡,导致mouseup事件无法被body捕获,导致拖动不能停止
                            var bodyWidth = $(\'body\').width();
                            var bodyHeight = $(\'body\').height();
                            $(\'body\').append(\'<div id="mask" style="opacity:0.2;top:0px;left:0px;background-color:green;position:absolute;z-index:9999;width:\'+bodyWidth+\'px;height:\'+bodyHeight+\'px;"></div>\');
                        }
                    }
                });

                $(\'body\').bind({
                    mousemove:function(e){
                        var ele = $(\'#myDiv\');
                        var rightPos = eleLeft + ele.width() + borderLen;
                        $(\'#pos\').text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+rightPos);

                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            ele.css(\'cursor\',\'e-resize\');
                        }else{
                            if(!isMouseDown){
                                ele.css(\'cursor\',\'auto\');
                            }
                        }
                        if(isMouseDown){
                            ele.width((e.pageX-eleLeft-borderLen)+\'px\'); 
                        }
                    },
                    mouseup:function(e){
                        isMouseDown = false;
                        $(\'#mask\').remove();
                    }
                });

                $(\'#otherDiv\').mouseup(function(e){
                    //e.preventDefault(); //阻止默认行为
                    e.stopPropagation(); //阻止事件冒泡(导致body捕获不到mouseup事件)
                });

 

4.完整代码和最终效果

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>div change width by drag</title>

        <script src="../jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
        
        
    </head>

    <body>
        <h1>div change width by drag</h1>
        
        <div id="pos" style="color:red"></div>
        
        
        <div id="myDiv" style="border:2px solid red;width:300px;height:50px;margin-left: 100px;margin-top: 20px"></div>

        <div id="otherDiv" style="border: 2px solid blue;width: 200px;height: 200px;margin-left: 400px"></div>
    </body>
    

    <script type="text/javascript">
            $(document).ready(function(){
                var eleLeft = $(\'#myDiv\').offset().left;
                var isMouseDown = false;
                var borderLen = 4; //左右边框

                $(\'#myDiv\').bind({
                    mousedown:function(e){
                        var ele = $(this);
                        var rightPos = eleLeft + ele.width() + borderLen;
                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            isMouseDown = true;

                            //创建遮罩层,防止mouseup事件被其它元素阻止冒泡,导致mouseup事件无法被body捕获,导致拖动不能停止
                            var bodyWidth = $(\'body\').width();
                            var bodyHeight = $(\'body\').height();
                            $(\'body\').append(\'<div id="mask" style="opacity:0.2;top:0px;left:0px;background-color:green;position:absolute;z-index:9999;width:\'+bodyWidth+\'px;height:\'+bodyHeight+\'px;"></div>\');
                        }
                    }
                });

                $(\'body\').bind({
                    mousemove:function(e){
                        var ele = $(\'#myDiv\');
                        var rightPos = eleLeft + ele.width() + borderLen;
                        $(\'#pos\').text("x:"+e.pageX + " eleLeft:"+eleLeft+" rightPos:"+rightPos);

                        if(rightPos-5 <= e.pageX && e.pageX <= rightPos){
                            ele.css(\'cursor\',\'e-resize\');
                        }else{
                            if(!isMouseDown){
                                ele.css(\'cursor\',\'auto\');
                            }
                        }
                        if(isMouseDown){
                            ele.width((e.pageX-eleLeft-borderLen)+\'px\'); 
                        }
                    },
                    mouseup:function(e){
                        isMouseDown = false;
                        $(\'#mask\').remove();
                    }
                });

                $(\'#otherDiv\').mouseup(function(e){
                    //e.preventDefault(); //阻止默认行为
                    e.stopPropagation(); //阻止事件冒泡(导致body捕获不到mouseup事件)
                });
            });
        </script>
</html>

 

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

js按下鼠标mousedown并mousemove的时候,如何保持鼠标样式全屏不变?

jQuery 通过鼠标摇拽改变div的大小

jquery如何通过拖动边框改变该div的大小

如何实现拖动修改网页中div模块大小

js中sortable怎么获取拖动的东西

js实现一个可以兼容PC端和移动端的div拖动效果