當前位置:才華齋>設計>網頁設計>

Javascript高階手勢使用介紹

網頁設計 閱讀(1.69W)

在IE10中新加入的對高階使用者輸入的識別支援,舉例說明:註冊一個點選操作,通過一句addEventListener 就能夠知道當前使用者的點選是哪種裝置,是手指的點選,是滑鼠的單擊還是觸控筆的點選(平板裝置都會帶有觸控筆)。

Javascript高階手勢使用介紹

ventListener("MSPointerDown",MyBack,false);

functionMyBack(e){

alert(ring());

}

以上這段程式碼就是能夠識別出當前使用者的點選是哪種裝置,通過回撥的方法中 terType 還進行判斷。滑鼠是4,觸控筆是3,手指是2。至於值為1是何種裝置還有待研究。

還有需要注意的就是 想在javascript中新增對輸入裝置的識別,註冊的方法事件也是有點點區別。

addEventListener 新增的`事件為 MSPointerDown

而在IE10中對於這樣的多種裝置識別中優先處理的手指的點選,前提是不影響功能正常單擊的情況下。然而IE10不僅僅能識別使用者的輸入裝置還支援非常多的高階手勢

以下為IE10高階手勢支援的演示

建立手勢物件

在您的網站中處理手勢的第一步是例項化手勢物件。

var myGesture = new MSGesture();

接下來,為該手勢提供一個目標元素。瀏覽器將對該元素觸發手勢事件。同時,該元素還可以確定事件的座標空間。

elm = lementById("someElement");

et = elm;

ventListener("MSGestureChange", handleGesture);

最後,告知手勢物件在手勢識別期間處理哪些指標。

ventListener("MSPointerDown", function (evt) {

// adds the current mouse, pen, or touch contact for gesture recognition

ointer(terId);

});

注意:請不要忘記您需要使用 –ms-touch-action 來配置元素以防止其執行預設觸控操作(例如,平移和縮放),併為輸入提供指標事件。

處理手勢事件

一旦手勢物件具有有效目標並至少添加了一個指標,則其將開始觸發手勢事件。手勢事件可分為兩種:靜態手勢(例如,點選或保持)和動態手勢(例如,收縮、旋轉和輕掃)。

點選

最基本的手勢識別是點選。當檢測到點選時,將會在手勢物件的目標元素觸發 MSGestureTap 事件。不同於單擊事件,點選手勢只能在使用者觸控、按滑鼠按鈕或使用手寫筆觸控而不移動時觸發。如果您要區分使用者點選元素和拖動元素的操作,這一點通常會顯得十分有用。

長按

長按手勢是指使用者使用一個手指觸控式螢幕幕,並保持片刻並抬起而不移動的操作。在長按互動期間,MSGestureHold 事件會針對手勢的各種狀態而多次觸發:

ventListener("MSGestureHold", handleHold);

function handleHold(evt) {

if (il & STURE_FLAG_BEGIN) {

// Begin signals the start of a gesture. For the Hold gesture, this means the user has been holding long enough in place that the gesture will become a complete press & hold if the finger is lifted.

}

if (il & STURE_FLAG_END) {

// End signals the end of the gesture.

}

if (il & STURE_FLAG_CANCEL) {

// Cancel signals the user started the gesture but cancelled it. For hold, this occurs when the user drags away before lifting. This flag is sent together with the End flag, signaling the gesture recognition is complete.

}

}

動態手勢(收縮、旋轉、輕掃和拖動)

動態手勢(例如,收縮或旋轉)將以轉換的形式報告,這與 CSS 2D 轉換頗為類似。動態手勢可觸發三種事件:MSGestureStart、MSGestureChange(隨著手勢的持續而重複觸發)和 MSGestureEnd。每個事件都包含縮放(收縮)、旋轉、轉換和速度等相關資訊。

由於動態手勢以轉換的形式報告,因此使用包含 CSS 2D 轉換的 MSGesture 來操作諸如照片或拼圖等元素將變得十分輕鬆。例如,您可以通過下列方式啟用縮放、旋轉和拖動元素的操作:

ventListener("MSGestureChange", manipulateElement);

function manipulateElement(e) {

// Uncomment the following code if you want to disable the built-in inertia provided by dynamic gesture recognition

// if (il == STURE_FLAG_INERTIA)

// return;

var m = new MSCSSMatrix(sform); // Get the latest CSS transform on the element

sform = m

slate(etX, etY) // Move the transform origin under the center of the gesture

te(tion * 180 / ) // Apply Rotation

e(e) // Apply Scale

slate(slationX, slationY) // Apply Translation

slate(etX, etY); // Move the transform origin back

}

縮放和旋轉等動態手勢可支援滑鼠操作,具體可通過在旋轉滑鼠滾輪的同時分別使用 CTRL 或 SHIFT 修飾鍵來實現。