1

我有以下代码:

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 在上下文 function(e) 和 中是什么意思e.touches[0].clientx

4

2 回答 2

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 和此处记录的其他触摸屏事件 看起来touches 是处理屏幕触摸的对象,因为我没有触摸屏设备我无法检查,但看起来触摸元素可以通过两种方式访问​​,第一种 - 使用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 的操作

于 2012-10-21T15:15:51.633 回答
0

onmousemove = onMouseMove is for HTML DOM event registration. in this case, it means method 'onMouseMove' should be invoked when there is a mouse move event on HTML element 'text-shadow-box'.

ontouchmove is another event that listens to any touch move, this happens on mobile clients (e.g. Android client). inside the event handler it uses the onMouseMove to handle this event by converting the touch point to client coordinate.

于 2012-10-21T15:14:21.790 回答