App下載

Html5如何實現(xiàn)滾動穿透?效果實現(xiàn)案例詳解!

猿友 2021-07-29 09:43:23 瀏覽數(shù) (2251)
反饋

對于前端開發(fā)人員來說簡單的實現(xiàn)靜態(tài)頁面創(chuàng)建是個比較簡單的過程,只有讓頁面動起來這樣才可以更受人歡迎,那么我們今天就來分享一個有關(guān)于:“Html5如何實現(xiàn)滾動穿透?效果實現(xiàn)案例詳解!”這個問題的相關(guān)內(nèi)容!

問題背景:

網(wǎng)站需要在移動端完成適配,針對移動端H5以及web端采用的都是bluma這種flex布局解決方案

在H5中使用的列表采用的是 react-virtualized 來繪制表格

為了展示表格中單行數(shù)據(jù)的具體詳情,通常的解決方案是采用新頁面或者是彈窗來完成。

這里采用的是彈窗的方案,點擊單行數(shù)據(jù)后的數(shù)據(jù)詳情用的是 bluma 的 modal-card。

具體細(xì)節(jié)和實例可以參考:https://bulma.io/documentation/components/modal/

問題詳情:

在點擊單行數(shù)據(jù)后,彈窗顯示詳情數(shù)據(jù),整個 modal-card 設(shè)置成 position:fixed;

沒有 footer 部分,設(shè)置 modal-card 的高度為整個屏幕的高度:100vh

表現(xiàn):

  • 在chrome瀏覽器中顯示,整個modal-card占滿整個屏幕
  • 在手機端顯示也是占滿,但是問題是,根據(jù)手勢移動,會將瀏覽器的搜索框部分往上頂,此時彈窗下面的數(shù)據(jù)列表頁能夠進(jìn)行滑動,之后彈窗的標(biāo)題覆蓋瀏覽器原搜索框部分,但這之間有延遲,能清晰看到下面頁面的數(shù)據(jù)
  • 在其他手機上會有另外一種顯示,如果滑動速度比較快,彈窗出現(xiàn)后立即滑動,就會看到在彈窗的底部就會出現(xiàn)一個小的空白,同樣彈窗下面的頁面能夠滾動,并且有明顯延遲和數(shù)據(jù)滾動顯示。

解決方案:

 modal-card 自身解決方案:

JS + CSS overflow:hidden

通過JS動態(tài)給彈窗下面的頁面html添加css類

if ($modalButtons.length > 0) {
    $modalButtons.forEach(function ($el) {
        $el.addEventListener('click', function () {
        var target = $el.dataset.target;
        openModal(target);
        });
    });
}

function openModal(target) {
    var $target = document.getElementById(target);
    rootEl.classList.add('is-clipped');
    $target.classList.add('is-active');
}

 

通過 overflow:hidden 來禁止頁面的滾動

is-clipped {
    overflow:hidden!important
}

當(dāng)彈窗關(guān)閉時,通過JS刪除掉頁面的 css 類:is-clipped

function closeModals() {
    rootEl.classList.remove('is-clipped');
    $modals.forEach(function ($el) {
        $el.classList.remove('is-active');
    });
}

但是這種方案在應(yīng)用中測試過后,發(fā)現(xiàn)并不能解決問題,上面的問題還是出現(xiàn)

position:fixed 方案

JS + CSS Position:fixed + scrollTop

方案思路:

  1. 彈窗時,將 html 的?position ?設(shè)置為 ?fixed?,將彈窗關(guān)閉后,將 html 的 postion 屬性取消。
  2. 因為列表頁會出現(xiàn)滾動的情況,而點擊的行有可能是在滾動發(fā)生后,所以需要計算html頁面本身的?scrollTop ?值。
  3. 因為彈窗時設(shè)置?position?為?fixed?后,?html?頁面的 ?scrollTop ?值會變成 0,會回到頁面頂部,所以在關(guān)閉彈窗后,需要手動設(shè)置html頁面的scrollTop 值,讓其滾動到html頁面原來的位置。
  4. 對于兼容性,需要設(shè)置不同屬性的 scrollTop 值

彈窗之前:

const scrollTop = global.document.documentElement.scrollTop || global.pageYOffset || global.document.body.scrollTop;
global.document.documentElement.style.position = 'fixed';
this.scrollTop = scrollTop;

關(guān)閉彈窗:

closeModalHandler = () => {
    const { closeOrderHistoryModal } = this.props;
    global.document.documentElement.style.position = '';
    global.pageYOffset = this.scrollTop;
    global.document.documentElement.scrollTop = this.scrollTop;
    global.document.body.scrollTop = this.scrollTop;
    closeOrderHistoryModal();
}

那么今天我們對于:“Html5如何實現(xiàn)滾動穿透?效果實現(xiàn)案例詳解!”這方面的相關(guān)內(nèi)容分享就到這邊啦!更多有關(guān)于html5這方面的使用我們都可以在W3Cschool中進(jìn)行學(xué)習(xí)和了解。希望小編的分享對大家的學(xué)習(xí)有所幫助! 

0 人點贊