图片滑动对比,极其丝滑!!!

234 阅读1分钟

简单介绍下思路

一、先将分割线定位在图片高度一半(居中)

        // 获取 .changed-img 元素的高度
        changedImgHeight = $(".changed-img").height();
        // 将 #clip 的初始高度设置为 .changed-img 高度的一半
        $("#bar").css("transform", `translate3d(0px, ${changedImgHeight / 2}px, 0px)`);
        $("#clip").css("clip", `rect(${changedImgHeight / 2}px, auto, auto, auto)`);
        

二、获取 #root 元素的顶部和底部纵坐标和监听鼠标的y轴坐标clickedclientY。根据不同事件,点击,移动,取消点击。

clickedclientY 记录初始点击时,鼠标的位置 changedImgHeight 上传图片的高度 moveY 通过clickedclientY和当前鼠标位置clientY(参数) ,计算用户的滑动距离和滑动方向 allow 是否允许滑动

                        <div id="root">
                            <img class="changed-img" id="firstImg" src="./image/1.png" />
                            <div id="clip">
                                <img class="origin-img" id="secondImg" src="./image/2.png" />
                            </div>
                            <div id="bar">
                                <div class="bar-line">
                                    <div class="handle-root">
                                        <div class="handle-line"></div>
                                        <div class="handle-button">
                                            <div></div>
                                            <div></div>
                                        </div>
                                        <div class="handle-line"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
        let clickedclientY
        // 获取 #root 元素的顶部和底部纵坐标
        const rootTop = $("#root").offset().top;
        const rootBottom = rootTop + $("#root").height();

        console.log(rootTop, rootBottom);
        // 点击
        const newclick = (clientY) => {
            console.log(clientY);
            clickedclientY = clientY;
            if (clientY < rootTop) {
                $("#bar").css("transform", `translate3d(0px, 0px, 0px)`);
                $("#clip").css("clip", `rect(auto, auto, 0px, auto)`);
                $("#root").css("cursor", `ns-resize`);
            }
            if (clientY > rootBottom ) {
                $("#bar").css("transform", `translate3d(0px, ${changedImgHeight}px, 0px)`);
                $("#clip").css("clip", `rect(${changedImgHeight}px, auto, auto, auto)`);
                $("#root").css("cursor", `ns-resize`);
            }
            if (clientY > rootTop && clientY < rootBottom) {
                $("#bar").css("transform", `translate3d(0px, ${clientY - rootTop}px, 0px)`);
                $("#clip").css("clip", `rect(${clientY - rootTop}px, auto, auto, auto)`);
                $("#root").css("cursor", `ns-resize`);
            }
        };
        // 移动
        const move = (clientY) => {
            console.log(clientY);
            if (clientY < clickedclientY) {
                let moveY = clickedclientY - clientY;
                $("#bar").css("transform", `translate3d(0px, ${Math.max(0, clientY - rootTop - moveY)}px, 0px)`);
                $("#clip").css("clip", `rect(${Math.max(0, clientY - rootTop - moveY)}px, auto, auto, auto)`);
                $("#root").css("cursor", `ns-resize`);
            } else {
                let moveY = clientY - clickedclientY;
                $("#bar").css("transform", `translate3d(0px, ${Math.min(changedImgHeight, clientY - rootTop + moveY)}px, 0px)`);
                $("#clip").css("clip", `rect(${Math.min(changedImgHeight, clientY - rootTop + moveY)}px, auto, auto, auto)`);
                $("#root").css("cursor", `ns-resize`);
            }
        };

        // 停止
        const stop = () => {
            allow = false;
            $("#root").css("cursor", "unset");
        };

有一说一,没必要判断clientY < rootTop 和 clientY > rootBottom 因为这些事件的触发我是写在 #root盒子上的,所以肯定是在clientY > rootTop && clientY < rootBottom 里面。

三、网页端鼠标触发事件和移动端触摸事件,并获取对应的y轴坐标

// 鼠标事件和触摸事件
        $("#root").on({
            mousedown: function (e) {
                allow = true;
                newclick(e.pageY); // 使用 e.pageY 替代 e.clientY
            },
            mousemove: function (e) {
                if (allow) {
                    move(e.pageY); // 使用 e.pageY 替代 e.clientY
                }
            },
            touchstart: function (e) {
                allow = true;
                newclick(e.originalEvent.touches[0].pageY); // 使用 e.originalEvent.touches[0].pageY 替代 e.originalEvent.touches[0].clientY
            },
            touchmove: function (e) {
                e.preventDefault();  // 阻止默认事件
                if (allow) {
                    move(e.originalEvent.touches[0].pageY); // 使用 e.originalEvent.touches[0].pageY 替代 e.originalEvent.touches[0].clientY
                }
            },
            mouseup: function () {
                stop();
            },
            touchend: function () {
                stop();
            },
        });

        $(document).on("mouseup touchend", () => {
            stop();
        });

四、网上在随便找个返回图片的接口,简单模拟一下。

document.getElementById('uploadimg').addEventListener('change', function (event) {
        const file = event.target.files[0];
        $("#loading").show();
        if (file) {
            const reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function (e) {
                const preview = document.getElementById('firstImg');
                preview.src = e.target.result;
                // 使用 FormData 构建表单数据
                const formData = new FormData();
                formData.append('imgdata', file);

                // 发送 AJAX 请求
                fetch('https://api.uomg.com/api/rand.img3?sort=胖次猫&format=json', {
                    method: 'POST',
                    // body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        changedImgHeight = $(".changed-img").height();
                        // 将 #clip 的初始高度设置为 .changed-img 高度的一半
                        $("#bar").css("transform", `translate3d(0px, ${changedImgHeight / 2}px, 0px)`);
                        $("#clip").css("clip", `rect(${changedImgHeight / 2}px, auto, auto, auto)`);
                        // 处理后端返回的数据
                        const resultDiv = document.getElementById('secondImg');
                        resultDiv.src = data.imgurl;
                        $("#loading").hide();
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            };
        }
    });

参考博文: juejin.cn/post/721661…