當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript适配移动端的移动元素方法
生活随笔
收集整理的這篇文章主要介紹了
JavaScript适配移动端的移动元素方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
難點:移動端與pc端的事件屬性不一樣,需要計算好偏移量才能跟著移動。
一、原理
首先需要獲取到點擊的位置距離元素el距離(top,left)
在添加移動事件:通過每次獲得移動獲得到在頁面的具體位置(x,y)
元素el所距離page邊框的距離為:
左邊距離 = x - left;
上邊距離 = y - left;
二、具體實現(xiàn)
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><div id="block"></div> </body> <style>#block {width: 100px;height: 100px;background-color: orangered;position: fixed;} </style><script>var el = document.querySelector("#block")var t1;var Top = 0;var Left = 0;function moveEl(e) {//判斷是否有延遲函數(shù)if (t1 != -1) {clearTimeout(t1);t1 = -1;}let clientY = e.clientY ?? e.touches[0].clientY;let clientX = e.clientX ?? e.touches[0].clientX;el.style.top = clientY - Top + "px";el.style.left = clientX - Left + "px";console.log(Top);}//鼠標點擊和觸屏點擊function mouseDown(e) {// 移動端無法直接獲取與父元素的位置信息,// 所以需要減去父元素與頁面的位置:parseInt(win.value.style.top)Top = e.offsetY ?? e.touches[0].pageY - parseInt(el.style.top || 0);Left = e.offsetX ?? e.touches[0].pageX - parseInt(el.style.left || 0);//取消拖動時會選中文字,不取消會出現(xiàn)事件無法取消bugdocument.body.onselectstart = document.body.ondrag = function () {return false;};// 添加事件window.addEventListener("mousemove", moveEl);// 適配觸摸屏window.addEventListener("touchmove", moveEl);}// 鼠標右鍵松開事件function mouseUp(e) {//取消拖動時不會選中文字document.body.onselectstart = document.body.ondrag = function () {return true;};// 移出事件window.removeEventListener("mousemove", moveEl);//適配觸摸window.removeEventListener("touchmove", moveEl);}// 鼠標移出事件function mouseOut() {//解決頻繁移出bugif (t1 != -1) return;//由于瀏覽器刷新有延遲需防抖移出t1 = setTimeout(() => {window.removeEventListener("mousemove", moveEl);}, 800);}el.addEventListener("mousedown", mouseDown)el.addEventListener("mouseup", mouseUp)el.addEventListener("mouseout", mouseOut)// 移動端事件el.addEventListener("touchstart", mouseDown)el.addEventListener("touchend", mouseUp)</script></html>總結
以上是生活随笔為你收集整理的JavaScript适配移动端的移动元素方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Helper辅助类设计技巧
- 下一篇: [EXtJS5学习笔记]第一节 Senc