生活随笔
收集整理的這篇文章主要介紹了
鼠标拖动生成画框
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求:鼠標按下拖動生成一個畫框
注意點:
div 的left和top:如果鼠標當前位置>鼠標起始位置,則為鼠標起始位置(鼠標往右拉);如果鼠標當前位置<鼠標起始位置,則為鼠標當前位置(鼠標往左拉);通過當前坐標x/y-鼠標起始坐標x/y得到要生成的div的寬度 ,如果往左拉,鼠標當前坐標-起始坐標可能為負數,所以,需要使用絕對值函數Math.abs();鼠標按下移動時動態獲取鼠標位置;
<!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>div {border: 1px solid black;position: absolute;}</style>
</head>
<body>
<script>
{//需求:鼠標按下拖動生成一個畫框let div = document.querySelector("div");document.addEventListener("mousedown",function(e){//鼠標按下時,生成一個divlet div = document.createElement("div");// document.body.appendChild(div);//獲取鼠標開始拖動的起始位置let startPos = {};startPos.x = e.clientX;startPos.y = e.clientY;function move(e){let curPos = {};curPos.x = e.clientX;curPos.y = e.clientY;// console.log(curPos);//div 的left和top:如果鼠標當前位置>鼠標起始位置,則為鼠標起始位置(鼠標往右拉);如果鼠標當前位置<鼠標起始位置,則為鼠標當前位置(鼠標往左拉)div.style.left = Math.min(startPos.x,curPos.x) + 'px';div.style.top = Math.min(startPos.y,curPos.y) + 'px';//通過當前坐標x/y-鼠標起始坐標x/y得到要生成的div的寬度 ,如果往左拉,鼠標當前坐標-起始坐標可能為負數,所以,需要使用絕對值函數Math.abs()div.style.width = Math.abs(curPos.x -startPos.x) + 'px';div.style.height = Math.abs(curPos.y -startPos.y) + 'px';document.body.appendChild(div);}//鼠標按下移動時動態獲取鼠標位置document.addEventListener("mousemove",move);//鼠標放下時,停止生成畫框document.addEventListener("mouseup",function(){document.removeEventListener("mousemove",move);},{once:true});});
}
</script>
</body>
</html>
總結
以上是生活随笔為你收集整理的鼠标拖动生成画框的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。