跳转到内容

❧ 可拖拽悬浮按钮-兼容移动PC

// 代码:
/**
* elementId String 拖拽元素ID
* iframeId String 拖拽区域存在的iframeID,可选
* distance Array 四边边距 [上,右,下,左],例如:[5,5,5,5]
* callback Function 点击事件回调函数
*/
function dragBtn({ elementId, iframeId, distance }, callback) {
if (!elementId) {
throw new Error('缺少拖拽元素ID');
}
if (distance && Object.prototype.toString.call(distance) != '[object Array]') {
throw new Error('边距距离为数组');
} else{
distance = []
}
let startEvt, moveEvt, endEvt, top, left, starX, starY, disX, disY, isClick = true;
// 判断是否支持触摸事件
if ('ontouchstart' in window) {
startEvt = 'touchstart'
moveEvt = 'touchmove'
endEvt = 'touchend'
} else {
startEvt = 'mousedown'
moveEvt = 'mousemove'
endEvt = 'mouseup'
}
// 拖动元素
const dragEle = document.getElementById(elementId);
// 存在的iframe
const iframeEle = document.getElementById(iframeId);
const moveFun = (event) => {
// 屏幕宽高
const screenHeight = document.documentElement.clientHeight;
const screenWidth = document.documentElement.clientWidth;
// 兼容IE浏览器
const e = event || window.event
// 鼠标坐标
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
// 判断是否是点击
if (Math.abs(starX - clientX) > 5 || Math.abs(starY - clientY) > 5) {
isClick = false;
}
left = clientX - disX;
top = clientY - disY;
// 垂直坐标
const minTop = distance[0] || 0;
const discBottom = distance[2] || 0;
const maxTop = screenHeight - dragEle.offsetHeight - discBottom;
if (top <= minTop) {
top = minTop;
} else if (top > maxTop) {
top = maxTop;
}
dragEle.style.top = top + 'px';
// 水平坐标
const minLeft = distance[3] || 0;
const discRight = distance[1] || 0;
const maxLeft = screenWidth - dragEle.offsetWidth - discRight;
if (left <= minLeft) {
left = minLeft;
} else if (left > maxLeft) {
left = maxLeft;
}
dragEle.style.left = left + 'px';
}
// 节流函数
const throttle = (fn, delay) => {
// 记录上一次函数触发的时间
var lastTime = 0;
return function() {
// 记录当前函数触发的时间
var nowTime = Date.now();
if (nowTime - lastTime > delay) {
// 修正this指向问题
fn.call(this);
// 同步时间
lastTime = nowTime;
}
}
}
const throttleFn = throttle(moveFun, 17);
const endFun = (e) => {
// 还原iframe事件触发
if (iframeEle) {
iframeEle.style.pointerEvents = "auto";
}
window.removeEventListener(moveEvt, throttleFn)
window.removeEventListener(endEvt, endFun)
// 点击
if (isClick && callback) {
callback();
}
}
dragEle.addEventListener(startEvt, function (event) {
isClick = true;
// div拖动遇到iframe卡顿的问题解决
if (iframeId) {
iframeEle.style.pointerEvents = "none";
}
// 阻止页面的滚动,缩放
event.preventDefault();
// 兼容IE浏览器
const e = event || window.event;
// 鼠标坐标
starX = e.touches ? e.touches[0].clientX : e.clientX;
starY = e.touches ? e.touches[0].clientY : e.clientY;
// 手指相对于拖动元素左上角的位置
disX = starX - dragEle.offsetLeft;
disY = starY - dragEle.offsetTop;
window.addEventListener(moveEvt, throttleFn);
window.addEventListener(endEvt, endFun);
});
}
// 使用:
dragBtn({elementId: 'btn'}, () => {
console.log('点击事件')
})