前端面試題-可拖拽元素的實現

可拖拽元素的實現

騰訊面試題(onMousemove, onMouseup, onMousedown)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .move {
      position: absolute;
      width: 100px;
      height: 100px;
      background: gray
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="move">
    </div>
  </div>
  
  <script>
  //獲取待拖拽元素
  let targetElem = document.querySelector('.move');
  let windowHeight, windowWidth; //窗口寬高
  let elemHeight, elemWidth; //元素寬高
  let ifDrag; //拖拽標誌
  let moveLeft, moveTop; //鼠標按下時的位置相對選中元素的位置的位移;

//鼠標按下-主要完成獲取位置座標工作
document.addEventListener('mousedown', function(e){
	if(e.target==targetElem){
	//獲取元素相對頁面視口的位置,即初始位置(x,y座標=左上角頂點座標)
		let targetElemLocate = targetElem.getBoundingClientRect(); 
		//激活拖拽標誌
		ifDrag = true;
		//頁面視口寬高(判斷邊界時使用)
		windowHeight = document.documentElement.clientHeight;
		windowWidth = document.documentElement.clientWidth;
		//獲取元素寬高(判斷邊界時使用)
		elemHeight = targetElem.clientHeight;
		elemWidth = targetElem.clientWidth;
		//鼠標按下時和選中元素的座標偏移量(初始偏移量,即鼠標和元素的距離,留待拖拽時使用)
		elemX = e.clientX - targetElemLocate.left;
		elemY = e.clientY - targetElemLocate.top;
	}
})

//鼠標放開事件
	document.addEventListener('mouseup', function(e){
		ifDrag = false;
})

//監聽鼠標移動事件
document.addEventListener('mousemove', function(e){
	if(ifDrag){
	// 鼠標移動後相對視口的位置-鼠標和選中元素的初始偏移量=選中元素當前座標位置(相對視口)
		let moveX = e.clientX - elemX; 
		let moveY = e.clientY - elemY;
		targetElem.style.left = moveX + 'px';
		targetElem.style.top = moveY + 'px';
		if(moveX<0){
		// 超出左邊界
			targetElem.style.left = 0;
		}
		if(moveY<0){
		// 超出上邊界
			targetElem.style.top = 0;
		}
		if(moveX + elemWidth > windowWidth){
		// 超出右邊界
			targetElem.style.left = windowWidth - elemWidth + 'px';
		}
		if(moveY + elemHeight > windowHeight){
		// 超出下邊界
			targetElem.style.top = windowHeight - elemHeight + 'px';
		}
	}
})
  
  </script>  
  </body>
  </html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章