TypechoJoeTheme

Dcr163的博客

统计

H5中Jquery实现按钮拖动

2024-08-10
/
0 评论
/
248 阅读
/
正在检测是否收录...
08/10

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;
            });

这样就能实现在手机上拖动按钮了~

拖动
朗读
赞(0)
版权属于:

Dcr163的博客

本文链接:

https://dcr163.cn/728.html(转载时请注明本文出处及文章链接)

评论 (0)