面试官:用原生js实现div拖拽,有边界条件哦!

1,413 阅读1分钟

主要通过三个鼠标事件---onmousedown、onmousemove、onmouseup来实现。 但要注意的是,onmousemove、onmouseup要针对document监听。如果针对div的话,只能向下或者向右移动。

同时要注意视图的几个距离的含义。

  • clientX,clientY---点击处距离当前窗口左边距离、上边距离。
  • offsetLeft、offsetTop---dom节点距离当前窗口左边距离、上边距离。
  • innerWidth、innerHeight---当前窗口的宽度和高度。

CSS

#drag {
            position: absolute;
            width: 100px;
            height: 100px;
            background: red;
            cursor: move;
        }

HTML

    <div id="drag"></div>

JS

function drag() {
            let drag = document.getElementById('drag');
            drag.onmousedown = function (e) {
                let diffX = e.clientX - drag.offsetLeft;//鼠标距box边框的距离
                let diffY = e.clientY - drag.offsetTop;

                document.onmousemove = function (e) {
                    let left = e.clientX - diffX;
                    let top = e.clientY - diffY;

                    //控制在视窗内
                    if (left < 0) {
                        left = 0
                    } else if (left > window.innerWidth - drag.offsetWidth) {
                        left = window.innerWidth - drag.offsetWidth;
                    }
                    if (top < 0) {
                        top = 0
                    } else if (top > window.innerHeight - drag.offsetHeight) {
                        top = window.innerHeight - drag.offsetHeight
                    }
                    drag.style.left = left + 'px';
                    drag.style.top = top + 'px'
                }
                document.onmouseup = function (e) {
                    // console.log(this);
                    this.onmousemove = null;
                    this.onmouseup = null;
                }
            }
        }
        drag()

记录记录!