專案中經常遇到這種需求,特此記錄下:
css部分:
html部分:
js部分(這裡分了兩種情況,因為pc端與移動端的處理情況有點不太一樣):
(1)、pc端
const winw =window.innerwidthconst winh =window.innerheight
const target = document.getelementbyid('target')
const targetw =target.offsetwidth
const targeth =target.offsetheight
const maxl = winw - targetw //
距離左側的最大距離
const maxt = winh - targeth //
距離頂部的最大距離
let posarr =
target.addeventlistener('mousedown', function
(e) )
document.addeventlistener('mousemove', function
(e)
else
if (left + deltax >= 0 && left + deltax <=maxl)
else
if (top + deltay >maxt)
else
if (top + deltay >= 0 && top + deltay <=maxt)
else
target.style.left = movex + 'px'target.style.top = movey + 'px'posarr =[x, y]
})
(2)、移動端,情況稍微有點不一樣,監聽的事件為touch事件,其次獲取元素當前位置也有點不一樣,具體**:
const winw =window.innerwidthconst winh =window.innerheight
const target = document.getelementbyid('target')
const targetw =target.offsetwidth
const targeth =target.offsetheight
const maxl = winw - targetw //
距離左側的最大距離
const maxt = winh - targeth //
距離頂部的最大距離
let posarr =
target.addeventlistener('touchstart', function
(e) )
document.addeventlistener('touchmove', function
(e)
else
if (left + deltax >= 0 && left + deltax <=maxl)
else
if (top + deltay >maxt)
else
if (top + deltay >= 0 && top + deltay <=maxt)
else
target.style.left = movex + 'px'target.style.top = movey + 'px'posarr =[x, y]
})
移動端 拖拽元素
1 觸控元素 touchstart 獲取手指初始座標,同時獲得盒子原來的位置 2 移動手指 touchmove 計算手指的滑動距離,並且移動盒子 3 離開手指 touchend e.targettouches 0 pagex e.targettouches 0 pagey 這兩個為手指移動時 在頁面...
vue移動端可拖拽功能
類似手機上桌面的小氣泡,可隨意拖動 1 首先在vue的公共元件中 components 新建個元件 拖拽滑動 default drag comp click gonext touchstart down touchmove move touchend end tel storeitems iconf...
pc端適配移動端
1.允許網頁寬度自動調整在網頁 的頭部,加入一行viewport元標籤所有主流瀏覽器都支援這個設定,包括ie9。對於那些老式瀏覽器 主要是ie6 7 8 需要使用css3 mediaqueries.js2.不使用絕對寬度由於網頁會根據螢幕寬度調整布局,所以不能使用絕對寬度的布局,也不能使用具有絕對寬...