2012-10-21 24 views
1

我有以下代碼:我先來看看對JavaScript

if(text && spot && box) { 
    document.getElementById('text-shadow-box').onmousemove = onMouseMove; 

    document.getElementById('text-shadow-box').ontouchmove = function(e) { 
     e.preventDefault(); 
     e.stopPropagation(); 

     onMouseMove({ 
      clientX: e.touches[0].clientX, 
      clientY: e.touches[0].clientY 
     }); 
    }; 
} 

什麼onmousemove = onMouseMove,爲什麼它在開始時沒有分配的?我的另一個問題:上下文功能(e)和e.touches[0].clientx中的含義是什麼?

+0

它分配一個函數在其他地方創建一個名爲onMouseMove的內置事件處理程序,名爲onmousemove – mplungjan

+0

「然後在函數中保留e和make」 - 你能改說這個嗎? – pimvdb

+0

@pimvdb - * W那麼'ontouchmove'確實可以做到,並且在函數中爲什麼使用'e'然後執行'e.touches [0] .clientx' * *。我認爲。 –

回答

0

onmousemove = onMouseMove用於HTML DOM事件註冊。在這種情況下,這意味着在HTML元素'text-shadow-box'上存在鼠標移動事件時,應該調用'onMouseMove'方法。

ontouchmove是監聽任何觸摸移動的另一個事件,這發生在移動客戶端(例如Android客戶端)上。在事件處理程序內部,它使用onMouseMove通過將觸點轉換爲客戶端座標來處理此事件。

+0

所以onMouseMove像變量我們通過? –

+0

是的,在JavaScript函數中是第一類對象,這意味着函數可以被分配給其他變量。 – Shuping

2

我會評論的代碼內聯:

//all variables ext,spot,box are defined, not "false" and not 0 and not null 
if (ext && spot && box) { 
/* We assign onmousemove event handler to the function, in javascript functions are vars 
* function declared like `function function_name(param) {}` go to global scope, 
* and almost equal to 'function_name=function(param) {}' 
* var local scope use `var function_name=function(param) {}` 
*/ 
      document.getElementById('text-shadow-box').onmousemove = onMouseMove; 
/* add here is another example, you attach ontouchmove anonymous function, 
* anonymous function BEGIN NEXT LINE */ 
      document.getElementById('text-shadow-box').ontouchmove = function (e) { 
// e here it is event object, which passed to handler function as argument 
//it is jquery call, mean do not start other event handlers after this line 
       e.preventDefault(); e.stopPropagation(); 
/* call function inMousemove, declared somewhere else 
      The "{ 
       clientX: e.touches[0].clientX, 
       clientY: e.touches[0].clientY 
      }" here is object having two properties - clientX and clientY */ 
       onMouseMove({ 
        clientX: e.touches[0].clientX, 
        clientY: e.touches[0].clientY 
       }); 
/* anonymous function END NEXT LINE */ 
      }; 


ontouchmove和其他觸摸屏事件documnted here 它看起來是 觸摸是對象,它處理的觸摸屏幕,因爲我沒有觸摸屏設備我無法檢查,但它看起來像被觸動的元素可以通過兩種方式訪問​​,第一種 - 使用 e.touches.item(n)(如doc中所述),第二種 - 使用e.touches作爲數組 e.touches[n]。 n == 0意味着第一個被觸動的元素,正如我從w3c規範中理解的那樣。
event.stopPropagation()

描述:向上冒泡DOM樹, 防止任何父處理程序從被通知該事件的阻止事件。

event.preventDefault()

說明:如果此方法被調用,事件 的默認動作不會被觸發。

所以event.stopPropagation()防止元素的任何父母接受該事件(比如你有兩個摺疊的div並且都具有事件偵聽器)

雖然event.preventDefault()防止默認動作(假設你有<a href="test.html"></a>,並有onclick事件處理程序,所以它是很好的防止行動,這將使瀏覽器加載test.html

+0

謝謝男人很好的答案,但是e.touches [0]做了什麼,爲什麼使用索引0和另一件事情e.preventDefault()和e.stopPropagation()之間的確切區別。 –

+0

我補充說明更多 –

+0

@eicto:好的工作。 +1 –