前言
实现在移动端的悬浮窗,可用作快捷移动菜单。
为了方便操作不遮挡界面主要信息,添加吸附在左右两侧的功能和动画效果。
点击可展开抽屉菜单,可更改为其他形式,例如:弹窗等。
代码展示
html
<div class="barrage"></div>
js
let disX, disY, moveX, moveY, starX, starY;
const winW = $(window).width();
const winH = $(window).height();
const halfContW = $('.barrage').width() / 2;
$('.barrage').on({
//绑定事件
touchstart: function (e) {
//手指按下时的坐标
starX = e.originalEvent.targetTouches[0].clientX;
starY = e.originalEvent.targetTouches[0].clientY;
disX = e.originalEvent.targetTouches[0].clientX - this.offsetLeft;
disY = e.originalEvent.targetTouches[0].clientY - this.offsetTop;
e.stopPropagation();
},
touchmove: function (e) {
let moveStartX = e.originalEvent.targetTouches[0].clientX,
moveStartY = e.originalEvent.targetTouches[0].clientY,
clientWidth = document.documentElement.clientWidth,
clientHeight = document.documentElement.clientHeight;
let L, T, starXEnd, starYEnd;
L = moveStartX - disX;
T = moveStartY - disY;
//移动时 当前位置与起始位置之间的差值
starXEnd = moveStartX - starX;
starYEnd = moveStartY - starY;
if (L < 0) {
//限制拖拽的X范围,不能拖出屏幕
L = 0;
} else if (L > clientWidth - this.offsetWidth) {
L = clientWidth - this.offsetWidth;
}
if (T < 0) {
//限制拖拽的Y范围,不能拖出屏幕
T = 0;
} else if (T > clientHeight - this.offsetHeight) {
T = clientHeight - this.offsetHeight;
}
moveX = L;
moveY = T;
this.style.left = moveX + 'px';
this.style.top = moveY + 'px';
this.style.transition = 'none';
e.stopPropagation();
},
touchend: function (e) {
if (moveX > winW / 2) {
moveX = winW - halfContW;
} else {
moveX = 0 - halfContW;
}
$(this).css({ left: moveX + 'px', transition: 'all 0.5s' });
e.stopPropagation();
},
// 点击时悬浮窗完全显示
click: function () {
$('.MainUI').show();
$('.ComMask').show();
const Left = Number(
this.style.left.substring(0, this.style.left.indexOf('px'))
);
if (Left < 0) {
this.style.left = '0px';
} else {
this.style.left = winW - $(this).width() + 'px';
}
},
});
// 此处为关闭抽屉菜单时的代码
$('.closeUI').on('click', function () {
$('.MainUI').hide();
$('.ComMask').hide();
hideBarrage();
});
// 隐藏一半悬浮窗
function hideBarrage() {
if (moveX > winW / 2) {
moveX = winW - halfContW;
} else {
moveX = 0 - halfContW;
}
$('.barrage').css({ left: moveX + 'px', transition: 'all 0.5s' });
}
其他
参考文章:https://blog.csdn.net/qq_39958629/article/details/90441003
参考了一部分逻辑,代码基本不一样了。
抽屉菜单代码是从《Top游戏中心》的公众号里面随意一个游戏里面扒下来的
demo示例图: