拖拽效果

html

<div id="ball"></div>

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';
			}
		);
posted @ 2019-08-23 20:34  $debug  阅读(177)  评论(0编辑  收藏  举报