關於js禁止瀏覽器縮放

 

前段時間因爲工做須要,須要實現禁止使用Ctrl/Command + -/+, 以及Ctrl/Command + 鼠標滾動等方式縮放瀏覽器:git

 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,再運行項目的時候忽然報錯:github

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

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}。chrome

暫時解決了問題,記錄一下待往後優化。瀏覽器

相關說明:優化

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

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

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

相關文章
相關標籤/搜索