拖拽效果

html


css

#ball{width: 100px; height: 100px; background: blue; border-radius: 50%; position: absolute;}

js

        function $elem(id){
            return document.getElementById(id);
        }

        let [enbleMove, ballOffsetX, ballOffsetY] = [false, 0, 0];
        //鼠标按下
        $elem('ball').addEventListener(
            'mousedown', e=>{
                [enbleMove, ballOffsetX, ballOffsetY] = [true, e.offsetX, e.offsetY];
                e.target.style.cursor = 'move';
            }
        );
        //鼠标移动
        window.addEventListener(
            'mousemove', e=>{
                if(enbleMove){
                    $elem('ball').style.top = (e.clientY - ballOffsetY) + 'px';
                    $elem('ball').style.left = (e.clientX - ballOffsetX) + 'px';
                }
            }
        );
        //鼠标弹起
        $elem('ball').addEventListener(
            'mouseup', e=>{
                enbleMove = false;
                e.target.style.cursor = 'default';
            }
        );

转载于:https://www.cnblogs.com/debug/p/11402466.html

你可能感兴趣的:(拖拽效果)