前段時間由於工作需要,需要實現禁止使用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
