jq实现页面区域内拖动功能
拖动逻辑
// 客服拖动功能
$(document).ready(function () {// 是否可以拖动let isDragging = false;// 拖动的元素let $currentElement = null;$(document).on("touchstart", "#app-service", function (e) {// 禁止页面滚动$("body").addClass("dragging");$currentElement = $(this);isDragging = true;const touch = e.originalEvent.touches[0];// 获取相对于视口的位置const rect = $currentElement[0].getBoundingClientRect();// 计算手指在元素内的偏移(相对于视口)const offsetX = touch.clientX - rect.left;const offsetY = touch.clientY - rect.top;$currentElement.data("dragOffset", { offsetX, offsetY });}).on("touchmove", "#app-service", function (e) {if (!isDragging || !$currentElement) return;const touch = e.originalEvent.touches[0];const dragOffset = $currentElement.data("dragOffset");// 计算新位置(相对于视口)let newX = touch.clientX - dragOffset.offsetX;let newY = touch.clientY - dragOffset.offsetY;// 🔒 边界限制const windowWidth = $(window).width();const windowHeight = $(window).height();const width = $currentElement.outerWidth();const height = $currentElement.outerHeight();newX = Math.max(0, Math.min(newX, windowWidth - width));newY = Math.max(0, Math.min(newY, windowHeight - height));// 更新位置(fixed 定位,left/top 是相对于视口)$currentElement.css({left: newX + "px",top: newY + "px",});}).on("touchend touchcancel", "#app-service", function () {if (isDragging) {// 取消禁止页面滚动$("body").removeClass("dragging");isDragging = false;$currentElement = null;}});
});
拖动元素
<div id="app-service"><img src="https://aff-im.bj.bcebos.com/onlineEnv/imsdk/assets/mobile-icon-3.png" alt="客服"></div>
样式
// 自定义客服样式
#app-service {position: fixed;top: 400px;right: 0;width: 60px;z-index: 99;/* 硬件加速,提升流畅度 */transform: translateZ(0);img {width: 100%;}
}
// 拖动客服禁止页面滚动
.dragging {overflow: hidden;
}