1. 程式人生 > 其它 >2021.0305穿透問題,解決ios軟鍵盤滑動問題

2021.0305穿透問題,解決ios軟鍵盤滑動問題

如何解決ios穿透問題

測試提出的問題,解決了幾個小時才研究出來,學藝不精,來這裡自己記錄一下,加深記憶也分享給大家

簡單資料穿透

一般穿透體現在彈窗上面,彈窗可以滑動,但背後的頁面是不可以滑動的,這個時候我們可以採用給父元素增添一個overflow:hidden的方式解決。

js 頁面
在這裡插入圖片描述
css 頁面
在這裡插入圖片描述

ios會出現 點選彈窗的輸入框,軟鍵盤展示,但下面的彈窗是可以拉動的。

解決辦法就要用的touchmove 事件
js 頁面

useEffect(() => {
        if (showCollegeSearch || showMajorSearch) {
            setTimeout(() => {
                const $mask = document.querySelector(
                    "#searchMask"  //這是我的遮罩層
                ) as HTMLElement;
                const $modal = document.querySelector(
                    "#collegeList"  //這是我的遮罩層的列表
                ) as HTMLElement;
                noScrollPenetration($mask, $modal)//這是我封裝的函式
                document
                    .querySelector("#inputBox")
                    ?.addEventListener("touchmove", (e) => e.preventDefault(), {
                        passive: false,   //阻止預設冒泡事件
                    });
                document
                    .querySelector("#clearBox")
                    ?.addEventListener("touchmove", (e) => e.preventDefault(), {
                        passive: false,
                    });
            }, 300);
        }
    }, [showCollegeSearch, showMajorSearch]);


另外封裝了一個 utils.js



export const noScrollPenetration = (
    $mask: HTMLElement,
    $modal: HTMLElement
) => {
    const listenerOpts = { passive: false };
    $mask.addEventListener(
        "touchmove",
        (e) => e.preventDefault(),
        listenerOpts
    );

    let startY = 0;

    $modal.addEventListener(
        "touchstart",
        (e) => {
            startY = e.targetTouches[0].clientY;
        },
        listenerOpts
    );

    $modal.addEventListener(
        "touchmove",
        (e) => {
            const modalHeight = $modal.clientHeight;
            const modalScrollHeight = $modal.scrollHeight;
            const scrollTop = $modal.scrollTop;
            const endY = e.targetTouches[0].clientY;
            const delta = endY - startY;
            //     alert(
            //         `scrolltop:${scrollTop},modalHeight:${modalHeight},modalScrollHeight:${modalScrollHeight},delta:${delta}`
            //     );

            if (
                (scrollTop === 0 && delta > 0) ||
                (scrollTop + modalHeight + 1 >= modalScrollHeight && delta < 0)
            ) {
                e.preventDefault();
                e.stopPropagation();
            }
        },
        listenerOpts
    );
};

希望可以幫到大家!掰掰~