pc+手机端客服按钮可以随意拖拽和拖动的,并且后面打开保留在之前位置(基于localStorage)

  • 内容
  • 评论
  • 相关
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>手机+pc拖动效果</title>
    <script src="https://wdfkshop.oss-cn-beijing.aliyuncs.com/static/cnadmin/js/jquery-1.9.1.min.js"
        type="text/javascript"></script>
    <style>
        .drag {
            position: fixed;
            bottom: 20px;
            right: 30px;
            width: 200px;
            height: 200px;
            background: red;
            cursor: pointer;
            border-radius: 300px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>

<body>

    <div class="drag"> <a link="tz">我可以被拖动</a></div>

    <script>
        var drag = $('.drag')[0];
        var drag_left = localStorage.getItem("drag_left");
        var drag_top = localStorage.getItem("drag_top");
        console.log(drag_left);
        console.log(drag_top);
        if (drag_left != '' || drag_top != '') {
            drag.style.left = drag_left;
            drag.style.top = drag_top;
        }

        var flag = false;
        var cur = {
            x: 0,
            y: 0
        }
        var nx, ny, dx, dy, x, y;
        function down() {
            flag = true;
            var touch;
            if (event.touches) {
                touch = event.touches[0];
            } else {
                touch = event;
            }
            cur.x = touch.clientX;
            cur.y = touch.clientY;
            dx = drag.offsetLeft;
            dy = drag.offsetTop;
        }
        function move() {
            if (flag) {
                var touch;
                if (event.touches) {
                    touch = event.touches[0];
                } else {
                    touch = event;
                }
                nx = touch.clientX - cur.x;
                ny = touch.clientY - cur.y;
                x = dx + nx;
                y = dy + ny;
                drag.style.left = x + "px";
                drag.style.top = y + "px";
                //存入本地的localstorage里面
                localStorage.setItem("drag_left", drag.style.left);
                localStorage.setItem("drag_top", drag.style.top);
                //阻止页面的滑动默认事件
                document.addEventListener("touchmove", function () {
                    event.preventDefault();
                }, false);
            }
        }
        //鼠标释放时候的函数
        function end() {
            flag = false;
        }

        if (isMobileDevice()) {
            // 手机设备
            drag.addEventListener("touchstart", function () {
                down();
            }, false)
            drag.addEventListener("touchmove", function () {
                move();
            }, false)
            drag.addEventListener("touchend", function () {
                end();
            }, false);
        } else {
            // 电脑浏览器
            drag.addEventListener("mousedown", function () {
                console.log("mousedown");
                $(window).on('mousemove', tuodong)
            }, false);
            drag.addEventListener("mousemove", function () {
                console.log("mousemove");

            }, false);
            document.documentElement.addEventListener("mouseup", function () {
                console.log("mouseup");
                $(window).off('mousemove');

            });

        }

        var tuodong = function (e) {
            var x = e.clientX;
            var y = e.clientY;
            $('.drag').css({
                left: (x - $('.drag').width() / 2) + 'px',
                top: (y - $('.drag').height() / 2) + 'px'
            })

            //存入本地的localstorage里面
            localStorage.setItem("drag_left", (x - $('.drag').width() / 2) + 'px');
            localStorage.setItem("drag_top", (y - $('.drag').height() / 2) + 'px');

        }


        function isMobileDevice() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        }


        //跳转
        $("[link=tz]").click(function () {
            window.location.href = "http://www.baidu.com";
        });


        //移动端防止下拉
        document.addEventListener('touchmove', function (event) {
            event.preventDefault();
        }, { passive: false });

    </script>
</body>

</html>

下面是生产环境优化后的代码:
<style>
    .drag {
        position: fixed;
        margin-bottom: 100px;
        z-index: 6666;
    }
</style>
<div class="drag" draggable="true">
    <img src="{$web_set_info['kefu_img']|default='/static/web/theme2/m/images/kefu1.png'}"
        style="width:50px;height:50px;">
</div>

<script>
    // 获取屏幕的宽度和高度
    var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    var drag = $('.drag')[0];
    var drag_left = localStorage.getItem("drag_left");
    var drag_top = localStorage.getItem("drag_top");
    console.log(drag_left);
    console.log(drag_top);
    if (drag_left || drag_top) {
        drag.style.left = drag_left;
        drag.style.top = drag_top;
    } else {

        //这里要把right和bottom转化成left和top的值
        //drag.style.right = "{$web_set_info['kefu_right_px']|default='10px'}";
        //drag.style.bottom = "{$web_set_info['kefu_bottom_px']|default='300px'}";
        var kefu_right_px = parseInt("{:cleanString($web_set_info['kefu_right_px'],10)}");
        var kefu_bottom_px = parseInt("{:cleanString($web_set_info['kefu_bottom_px'],300)}");
        drag.style.left = (screenWidth - 50 - kefu_right_px) + "px";
        drag.style.top = (screenHeight - 50 - kefu_bottom_px) + "px";

    }

    var flag = false;
    var cur = {
        x: 0,
        y: 0
    }
    var nx, ny, dx, dy, x, y;
    function down() {
        console.log("down", "执行到了down");
        flag = true;
        var touch;
        if (event.touches) {
            touch = event.touches[0];
        } else {
            touch = event;
        }

        console.log("touch", touch);

        cur.x = touch.clientX;
        cur.y = touch.clientY;
        dx = drag.offsetLeft;
        dy = drag.offsetTop;
    }
    function move() {
        if (flag) {
            var touch;
            if (event.touches) {
                touch = event.touches[0];
            } else {
                touch = event;
            }
            console.log("cur", cur);

            nx = touch.clientX - cur.x;
            ny = touch.clientY - cur.y;
            x = dx + nx;
            y = dy + ny;

            // 获取屏幕的宽度和高度
            var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            //console.log("screenWidth",screenWidth);
            //console.log("screenHeight",screenHeight);

            // 获取拖拽元素的宽度和高度
            var dragWidth = drag.offsetWidth;
            var dragHeight = drag.offsetHeight;

            //console.log("dragWidth",dragWidth);
            //console.log("dragHeight",dragHeight);

            // 计算元素的左边界和上边界
            var leftBoundary = 0;
            var topBoundary = 0;

            // 计算元素的右边界和下边界
            var rightBoundary = screenWidth - dragWidth;
            var bottomBoundary = screenHeight - dragHeight;

            //console.log("rightBoundary",rightBoundary);
            //console.log("bottomBoundary",bottomBoundary);

            console.log("x", x);
            console.log("y", y);

            // 确保拖拽元素的位置在屏幕可视范围内
            x = Math.min(Math.max(x, leftBoundary), rightBoundary);
            y = Math.min(Math.max(y, topBoundary), bottomBoundary);




            drag.style.left = x + "px";
            drag.style.top = y + "px";
            //存入本地的localstorage里面
            localStorage.setItem("drag_left", drag.style.left);
            localStorage.setItem("drag_top", drag.style.top);

            //console.log(drag.style.left);
            //console.log(drag.style.top);
        }
    }

    //鼠标释放时候的函数
    function end() {
        flag = false;
    }


    var flag1 = 0; // 标记是拖曳还是点击
    if (isMobileDevice()) {
        // 手机设备
        drag.addEventListener("touchstart", function (event) {
            down();
            //移动的时候防止冒泡
            flag1 = 0;
            console.log("touchstart");
            event.preventDefault();

        }, false)
        drag.addEventListener("touchmove", function () {
            move();
            flag1 = 1;
            console.log("touchmove");

        }, false)
        drag.addEventListener("touchend", function (event) {
            end();
            console.log("touchend");
            if (flag1 == 0) { // 点击
                console.log("click");
                window.location.href = "{$web_set_info['kefu_url']}";
                return;
            } else if (flag1 == 1) { // 拖曳
                console.log("touchmove");

            }

        }, false);
    } else {

        // 电脑浏览器
        /*
        var offsetX, offsetY;
        var isDragging = false;
        var mouseDownTime;

        drag.addEventListener('mousedown', function (event) {
            offsetX = event.clientX - drag.offsetLeft;
            offsetY = event.clientY - drag.offsetTop;
            isDragging = true;
            // 记录鼠标按下时间
            mouseDownTime = Date.now();
            // 阻止默认的文本选择行为
            event.preventDefault();
        });

        document.addEventListener('mousemove', function (event) {
            console.log("mousemove");
            if (isDragging) {
                tuodong(event);
            }
        });

        document.addEventListener('mouseup', function () {
            var currentTime = Date.now();
            var timeDiff = currentTime - mouseDownTime;

            if (timeDiff <= 200) { // 200毫秒内视为点击操作
                console.log("click");
                window.location.href = "{$web_set_info['kefu_url']}";
            } else { // 否则视为拖拽操作
                console.log("touchmove");
            }
            isDragging = false;
        });
        */
        var offsetX, offsetY;

        drag.addEventListener('dragstart', function (event) {
            console.log("dragstart");

        });
        document.addEventListener('drag', function (event) {
            console.log("drag");
            console.log(event);
            return;
        });
        document.addEventListener('dragend', function (event) {
            tuodong(event);
            return;
        });

        $(".drag").click(function () {
            console.log("点击了");
            window.location.href = "{$web_set_info['kefu_url']}";
            return;
        });

    }
    var tuodong = function (e) {
        var x = e.clientX;
        var y = e.clientY;
        $('.drag').css({
            left: (x - $('.drag').width() / 2) + 'px',
            top: (y - $('.drag').height() / 2) + 'px'
        })
        //存入本地的localstorage里面
        localStorage.setItem("drag_left", (x - $('.drag').width() / 2) + 'px');
        localStorage.setItem("drag_top", (y - $('.drag').height() / 2) + 'px');

    }

    var tuodong1 = function (event) {
        var left = event.clientX;
        var top = event.clientY;
        console.log(left);
        console.log(top);

        drag.style.left = left + 'px';
        drag.style.top = top + 'px';
        //存入本地的localstorage里面
        localStorage.setItem("drag_left", left + 'px');
        localStorage.setItem("drag_top", top + 'px');

    }

    function isMobileDevice() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }




</script>

<!--
<script src="https://unpkg.com/vconsole/dist/vconsole.min.js"></script>
<script>
  // VConsole 默认会挂载到 `window.VConsole` 上
  var vConsole = new window.VConsole();
</script>
-->

 

本文标签:

版权声明:若无特殊注明,本文皆为《菜鸟站长》原创,转载请保留文章出处。

本文链接:pc+手机端客服按钮可以随意拖拽和拖动的,并且后面打开保留在之前位置(基于localStorage) - http://wziyi.com.cn/?post=413

发表评论

电子邮件地址不会被公开。 必填项已用*标注