js拖拽

JS拖拽事件

首先,要有以下几个动作:
①鼠标按下
②鼠标移动
③鼠标松开

一.mousedown、mousemove和mouseup 拖着目标元素在页面任意位置
如果要设置物体拖拽,那么必须使用三个事件,并且这三个事件的使用顺序不能颠倒。

1.onmousedown:鼠标按下事件
2.onmousemove:鼠标移动事件
3.onmouseup:鼠标抬起事件

重点:

1、一定要绝对定位,脱离文档流才可以移动。

2、绑定拖拽的元素,移动和鼠标松开后是对document的绑定,因为移动的是整个div。

3、点击:a= 获取当前鼠标坐标、b =div距浏览器距离、c = 鼠标在div内部距离=a-b。

移动:通过 a - c 建立鼠标与div的关系,防止鼠标超出div。

基本思路:(以下来自网络)

拖拽状态 = 0鼠标在元素上按下的时候{

拖拽状态 = 1

记录下鼠标的x和y坐标

记录下元素的x和y坐标

}

鼠标在元素上移动的时候{

如果拖拽状态是0就什么也不做。

如果拖拽状态是1,那么

元素y = 现在鼠标y - 原来鼠标y + 原来元素y

元素x = 现在鼠标x - 原来鼠标x + 原来元素x

}

鼠标在任何时候放开的时候{

拖拽状态 = 0

}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0;
            top: 0;
        }
        #div2{
            width: 100px;
            height: 100px;
            background: yellow;
            position: absolute;
            left: 500px;
            top: 200px;

        }
    </style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
<script>
    var div1=document.getElementById('div1')
    div1.onmousedown=function (event) {
console.log(event.clientX)
        console.log(div1.offsetLeft)//div1的left值
        var chaX=event.clientX-div1.offsetLeft
        div1.onmousemove=function (event){
    console.log(event.clientX)
            div1.style.left=event.clientX-chaX+'px'
        }
        document.onmouseup=function () {
document,onmousemove=null
        }
    }

    document.onmousemove=function (event) {
    div1.style.left=event.clientX-chaX+'px'
        div1.style.top=event.clientY-chaY+'px'
        console.log(div1.offsetWidth/2,div2.offsetWidth/2,'半径')
        console.log(div2.offsetLeft-div1.off)
    }

</script>

 

上一篇:javascript中的闭包解析


下一篇:Qt窗口置顶与激活