jQuery事件键码标准化

时间:2012-11-01 10:18:05

标签: javascript jquery

我读到所有jQuery事件中的which参数都已规范化(specified here)。 但是,我试图弄清楚源代码(jQuery)的位置,实现了这种规范化。我有兴趣弄清楚它是如何完成的。有人有想法吗?你能指出我正确的方向还是在这里发布解释?

1 个答案:

答案 0 :(得分:1)

检查keyHooksmouseHooks的{​​{3}}:

keyHooks: {
    props: "char charCode key keyCode".split(" "),
    filter: function( event, original ) {

        // Add which for key events
        if ( event.which == null ) {
            event.which = original.charCode != null ? original.charCode : original.keyCode;
        }

        return event;
    }
},

mouseHooks: {
    props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
    filter: function( event, original ) {
        var eventDoc, doc, body,
            button = original.button,
            fromElement = original.fromElement;

        // Calculate pageX/Y if missing and clientX/Y available
        if ( event.pageX == null && original.clientX != null ) {
            eventDoc = event.target.ownerDocument || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
            event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        // Add relatedTarget, if necessary
        if ( !event.relatedTarget && fromElement ) {
            event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
        }

        // Add which for click: 1 === left; 2 === middle; 3 === right
        // Note: button is not normalized, so don't use it
        if ( !event.which && button !== undefined ) {
            event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
        }

        return event;
    }
},