關於js禁止瀏覽器縮放


 

前段時間由於工作需要,需要實現禁止使用Ctrl/Command + -/+, 以及Ctrl/Command + 鼠標滾動等方式縮放瀏覽器:

 1         $(document).keydown(function (event) {
 2           //event.metaKey mac的command鍵 
 3           //mac下chrome: - 189, + 187 firefox: - 173, + 61, 
 4           //數字鍵盤: + 107, - 109
 5           if ((event.ctrlKey === true || event.metaKey === true)&& 
 6           (event.which === 189 || event.which === 187 
 7           || event.which === 173 || event.which === 61 
 8           || event.which === 107  || event.which === 109))
 9           {
10             event.preventDefault();
11           }
12         });
13         $(window).bind('mousewheel DOMMouseScroll', function (event) {
14           if (event.ctrlKey === true || event.metaKey) {
15              event.preventDefault();
16           }
17         });

然而最近升級了chrome瀏覽器到73,再運行項目的時候突然報錯:

查看了相關說明,發現chrome73為了減少用戶觸摸屏幕后更新顯示所需的時間,將在文檔級目標(窗口)上注冊的wheel/mousewheel事件偵聽器默認為passive(即:{passive: true})。而這樣的設置將忽略此類偵聽器內部的preventDefault()調用,從而使chrome下的禁止功能失效。目前先根據官方說明做了修改:

window.addEventListener('mousewheel', function(event){
    if (event.ctrlKey === true || event.metaKey) {
          event.preventDefault();
    }
},{ passive: false});

//firefox
 window.addEventListener('DOMMouseScroll', function(event){
    if (event.ctrlKey === true || event.metaKey) {
           event.preventDefault();
    }
},{ passive: false});

雖然目前firefox的相關更改還在考慮中,但為了防止出現相同問題,還是為ff下的事件顯示設置了{passive: true}。

暫時解決了問題,記錄一下待日后優化。

相關說明:

https://www.chromestatus.com/features/6662647093133312

https://developers.google.com/web/updates/2017/01/scrolling-intervention

https://github.com/WICG/interventions/issues/64


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM