在移動端頁面開發中,有時需要禁止用戶滑動屏幕,搜索了好久才找到移動終端的touch事件,touchstar,touchmove,touchend.
阻止滾動
一些移動設備有缺省的touchmove行為,比如說經典的iOS overscroll效果,當滾動超出了內容的界限時就引發視圖反彈。這種做法在許多多點觸控應用中會帶來混亂,但要禁用它很容易。
document.body.addEventListener('touchmove', function(event) {
event.preventDefault();
}, false);
具體參見 移動互聯網終端的touch事件,touchstart, touchend, touchmove
在PC端頁面開發中,可以設置onmousewheel,其實在大多數瀏覽器(IE6, IE7, IE8, Opera 10+, Safari 5+)中,都提供了 “mousewheel” 事件。但杯具的是 Firefox 3.5+ 卻不支持此事件,不過慶幸 Firefox 3.5+ 中提供了另外一個等同的事件:”DOMMouseScroll” (事件和事件屬性的測試案例)。
var addEvent = (function(){ if (window.addEventListener) { return function(el, sType, fn, capture) { el.addEventListener(sType, fn, (capture)); }; } else if (window.attachEvent) { return function(el, sType, fn, capture) { el.attachEvent("on" + sType, fn); }; } else { return function(){}; } })(), stopEvent: function(event) { if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, zoomIn = function(){}, zoomOut = function(){}, // isFirefox 是偽代碼,大家可以自行實現 mousewheel = isFirefox ? "DOMMouseScroll" : "mousewheel"; // object 是偽代碼,你需要注冊 Mousewheel 事件的元素 addEvent(object, mousewheel, function(event){ var delta = 0; event = window.event || event; stopEvent(event); delta = event.wheelDelta ? (event.wheelDelta / 120) : (- event.detail / 3); // zoomIn, zoomOut 是偽代碼,需要實現的縮放事件 delta > 0 ? zoomIn(delta): zoomOut(Math.abs(delta)); } , false);
具體參見淺談 Mousewheel 事件