Shadow
H5中Jquery实现按钮拖动
H5中Jquery实现按钮拖动
直接上代码:
var draggableElement = $('#fix-navs');
draggableElement.height(draggableElement.height()+'px'); //设置高度,避免拖动下面会挡住页面
var isDragging = false;
var touchStartX, touchStartY, touchMoveX, touchMoveY;
var elementWidth = draggableElement.width();
var elementHeight = draggableElement.height();
// 获取屏幕尺寸
var screenWidth = $(window).width()-8;
var screenHeight = $(window).height()-20;
// 初始化触摸点相对于元素的位置
draggableElement.on('touchstart', function (event) {
isDragging = true;
touchStartX = event.originalEvent.touches[0].pageX - draggableElement.position().left;
touchStartY = event.originalEvent.touches[0].pageY - draggableElement.position().top;
});
$(document).on('touchmove', function (event) {
if (isDragging) {
touchMoveX = event.originalEvent.touches[0].pageX - touchStartX;
touchMoveY = event.originalEvent.touches[0].pageY - touchStartY;
// 计算新位置
var newX = Math.max(0, Math.min(screenWidth - elementWidth, touchMoveX));
var newY = Math.max(0, Math.min(screenHeight - elementHeight, touchMoveY));
draggableElement.css({
'left': newX + 'px',
'top': newY + 'px'
});
}
});
$('#fix-navs').on('click', function () {
if (!isDragging) {
draggableElement.trigger('touchstart');
} else {
draggableElement.trigger('touchend');
}
});
// 结束拖动
draggableElement.on('touchend', function () {
isDragging = false;
});
这样就能实现在手机上拖动按钮了~
Dcr163的博客
https://dcr163.cn/728.html(转载时请注明本文出处及文章链接)