鼠标拖动窗口

192 阅读1分钟

一.思路。

1.先画个定位的DIV
2.监听Mousedown  mouseup  mousemove
3.定义一个变量来标记是否按下
4.在Move中判断如果按下,则将鼠标位置赋值给div
5.按下时记录鼠标与div的相对位置,移动时减去这段距离
6.在move时阻止默认行为,防止拖动文字有Bug
7.监听blur事件,防止窗口失去焦点导致bug

 <div id="demo">asdfasf1111</div>
<script>
    //获取元素。
    let demo = document.querySelector('#demo')
    let canMove = false
    let x = 0, y = 0
    //鼠标按下事件
    demo.onmousedown = function (e) {
        x = e.pageX - demo.offsetLeft
        y = e.pageY - demo.offsetTop
        canMove = true
    }
    console.log(demo.offsetLeft);
    
    //demo自定义右键窗口
    demo.oncontextmenu = function (e) {
        e.preventDefault()//阻止默认行为
        console.log('右键了');
    }
    //鼠标松开事件
    window.onmouseup = function () {
        canMove = false
    }
    //当前窗口失去焦点。
    window.onblur = function () {
        canMove = false
    }
    //鼠标移动事件
    window.onmousemove = function (e) {
        e.preventDefault(); //阻止默认行为
        if (canMove) {
            let left = e.pageX - x
            let top = e.pageY - y
            if (left < 0) left = 0
            if (top < 0) top = 0
            let maxLeft = window.innerWidth - demo.offsetWidth
            let maxTop = window.innerHeight - demo.offsetHeight
            if (left > maxLeft) left = maxLeft
            if (top > maxTop) top = maxTop
            demo.style.left = left + "px"
            demo.style.top = top + 'px'
        }
    }
</script>
样式:
    <style>
    #demo {
        width: 300px;
        height: 300px;
        background: #ccc;
        /* user-select: none; */
        position: absolute;
    }
</style>