日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

鼠标拖动生成画框

發布時間:2023/12/14 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 鼠标拖动生成画框 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

需求:鼠標按下拖動生成一個畫框

注意點:

  • 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>

    總結

    以上是生活随笔為你收集整理的鼠标拖动生成画框的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。