Table of Contents
1. Automatically obtain focus
2. Listening to keyboard events
3. Key event screening
4. Event distribution
5. Event subscription and unsubscription
6. Extend the custom event type
Home Web Front-end JS Tutorial Introduction to jQuery-based keyboard event listening control (code example)

Introduction to jQuery-based keyboard event listening control (code example)

Apr 04, 2019 am 09:15 AM
javascript jquery

This article brings you an introduction to the jQuery-based keyboard event listening control (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In a recent project, I want to make a drawing board, which needs to monitor keyboard events to perform operations such as undo, redo, move, zoom, etc., so I easily implemented a keyboard event monitoring control, and gained a little during the process. I have sorted it out, I hope it will be helpful to everyone, and I hope to get some advice from experts.

1. Automatically obtain focus

It seems that the browser's keyboard events can only be set to listen to those elements that can obtain focus, and usually need to listen for events

, No element can get focus, so you need to modify some properties of the target element so that it can get focus. Another possible method is to delegate the event to a tag such as . The first type of method is used here. Of course, there is more than one attribute that can be modified. For example, for the

tag, you can set its "editable" attribute to true, but what is used here is to set a tabindex value for it. . The code is as follows:

$ele.attr('tabindex', 1);
Copy after login

In addition, the triggering of the focus event requires clicking on the element or TAB switching, which is not in line with human intuition. Therefore, it is necessary to monitor the mouse move-in event so that the target element can "automatically" gain focus:

$ele.on('mouseenter', function(){
    $ele.focus();
});
Copy after login

2. Listening to keyboard events

Since the browser used by the customers for the project is mainly chrome (actually 36x browser), no adaptation has been made to the browser. Only jQuery's event monitoring is used:

        $ele.on('keydown', this._keyDownHandler.bind(this));
Copy after login

Since the implementation is control-oriented, a private method _keyDownHandler is defined to respond to keyboard actions.

3. Key event screening

jQuery event listener returns a lot of event object information, so it needs to be screened. For this purpose, a private method _keyCodeProcess is defined to handle key presses

function _keyCodeProcess(e){
        var code = e.keyCode + '';
        var altKey = e.altKey;
        var ctrlKey = e.ctrlKey;
        var shiftKey = e.shiftKey;

        var threeKey = altKey && ctrlKey && shiftKey;
        var ctrlAlt = altKey && ctrlKey;
        var altShift = altKey && shiftKey;
        var ctrlShift = shiftKey && ctrlKey;

        var keyTypeSet = this.keyTypeSet;
        var resStr = '';

        if(threeKey){
            resStr = keyTypeSet.threeKey[code];
        } else if(ctrlAlt) {
            resStr = keyTypeSet.ctrlAlt[code];
        } else if(ctrlShift) {
            resStr = keyTypeSet.ctrlShift[code];
        } else if(altShift) {
            resStr = keyTypeSet.altShift[code];
        } else if(altKey) {
            resStr = keyTypeSet.altKey[code];
        } else if(ctrlKey) {
            resStr = keyTypeSet.ctrlKey[code];
        } else if(shiftKey) {
            resStr = keyTypeSet.shiftKey[code];
        } else {
            resStr = keyTypeSet.singleKey[code];
        }

        return resStr
    };
Copy after login

The keyTypeSet here is an object similar to a lookup table, which stores various types of combinations of ctrl, shift, and alt buttons. Under each combination, a custom event type string is stored according to the key code. When the event occurs This string will be returned from here later. Of course, when there is no corresponding custom event, an empty string will be returned honestly.

4. Event distribution

_keyCodeProcess method extracts the event type from the event. We store the listening callback function in a lookup table callback in advance, and "cleverly" make its key The name just adds "on" prefix in front of the custom event string, and it can be easily called. The aforementioned _keyDownHandler is designed for this:

function _keyDownHandler(e){
        var strCommand = this._keyCodeProcess(e);

        var objEvent = {
            type: '',
            originEvent: e.originEvent
        };

        strCommand && this.callback['on' + strCommand](objEvent);

        return null;
    };
Copy after login

5. Event subscription and unsubscription

As mentioned earlier, we store the callback function and call it in a timely manner, so we need to expose a "subscription" interface so that developers can easily store their callback function into the object instance. For this reason, I defined a .bind interface:

function bind(type, callback, description){
        var allType = this.allEventType;
        if(allType.indexOf(type) === -1){
            throwError('不支持改事件类型,请先扩展该类型,或采用其他事件类型');
        }

        if(!(callback instanceof Function)){
            throwError('绑定的事件处理回调必须是函数类型');
        }

        this.callback['on' + type] = callback;

        this.eventDiscibeSet[type] = description || '没有该事件的描述';

        return this;
    };
Copy after login

Since it is for human use, I did a type check by the way.
According to the "symmetry" of the interface, it is best to subscribe and unsubscribe, so the .unbind interface is defined, with only one line of code, and the implementation is as follows:

function unbind(type){
        this.callback['on' + type] = this._emptyEventHandler;

        return this;
    };
Copy after login

6. Extend the custom event type

The combinations of keyboard events are rich and colorful. If they are all built into the control, it will be very bloated. Therefore, in addition to a few common key combinations, developers can customize key combinations and returns through the .extendEventType method. String:

function extendEventType(config){
        var len = 0;
        if(config instanceof Array){
            len = config.length;
            while(len--){
                this._setKeyComposition(config[len]);
            }
        } else {
            this._setKeyComposition(config);
        }
        return this;
    };
Copy after login

The ._setKeyComposition is a private method used to write custom keyboard events:

_setKeyComposition(config){
        var altKey = config.alt;
        var ctrlKey = config.ctrl;
        var shiftKey = config.shift;

        var threeKey = altKey && ctrlKey && shiftKey;
        var ctrlAlt = altKey && ctrlKey;
        var altShift = altKey && shiftKey;
        var ctrlShift = shiftKey && ctrlKey;
        var code = config.code + '';

        if(threeKey){
            this.keyTypeSet.threeKey[code] = config.type;
        } else if(ctrlAlt) {
            this.keyTypeSet.ctrlAlt[code] = config.type;
        } else if(ctrlShift) {
            this.keyTypeSet.ctrlShift[code] = config.type;
        } else if(altShift) {
            this.keyTypeSet.altShift[code] = config.type;
        } else if(altKey) {
            this.keyTypeSet.altKey[code] = config.type;
        } else if(ctrlKey) {
            this.keyTypeSet.ctrlKey[code] = config.type;
        } else if(shiftKey) {
            this.keyTypeSet.shiftKey[code] = config.type;
        } else {
            this.keyTypeSet.singleKey[code] = config.type;
        }

        return null;
    };
Copy after login

In this way, a keyboard event listening control is complete, as follows Is the complete implementation code:

/**
 * @constructor 键盘事件监听器
 * */
function KeyboardListener(param){
    this._init(param);
}

!function(){
    /**
     * @private {String} param.ele 事件对象选择器
     * */
    KeyboardListener.prototype._init = function _init(param){
        this.$ele = $(param.ele);

        this._initEvents();

        this._initEventType();

        return null;
    };

    /**
     * @private _emptyEventHandler 空白事件响应
     * */
    KeyboardListener.prototype._emptyEventHandler = function _emptyEventHandler(){
        return null;
    };

    /**
     * @private _initEventType 初始化所有初始自定义事件类型
     * */
    KeyboardListener.prototype._initEventType = function _initEventType(){
        var allType = ['up', 'down', 'left', 'right', 'undo', 'redo', 'zoomIn', 'zoomOut', 'delete'];
        var intLen = allType.length;
        this.allEventType = allType;
        this.callback = {};
        this.eventDiscibeSet = {};

        for(var intCnt = 0; intCnt < intLen; intCnt++){
            this.callback[&#39;on&#39; + allType[intCnt]] = KeyboardListener.prototype._emptyEventHandler;
        }

        return null;
    };

    /**
     * @private _initEvents 绑定 DOM 事件
     * */
    KeyboardListener.prototype._initEvents = function _initEvents(){
        var $ele = this.$ele;

        $ele.attr(&#39;tabindex&#39;, 1);

        $ele.on(&#39;mouseenter&#39;, function(){
            $ele.focus();
        });

        $ele.on(&#39;keydown&#39;, this._keyDownHandler.bind(this));

        this.keyTypeSet = {
            altKey: {},
            ctrlAlt: {},
            ctrlKey: {},
            threeKey: {},
            altShift: {},
            shiftKey: {},
            ctrlShift: {},
            singleKey: {}
        };

        // 支持一些内建的键盘事件类型
        this.extendEventType([
            {
                type: &#39;redo&#39;,
                ctrl: true,
                shift: true,
                code: 90
            },
            {
                type: &#39;undo&#39;,
                ctrl: true,
                code: 90
            },
            {
                type: &#39;copy&#39;,
                ctrl: true,
                code: 67
            },
            {
                type: &#39;paste&#39;,
                ctrl: true,
                code: 86
            },
            {
                type: &#39;delete&#39;,
                code: 46
            },
            {
                type: &#39;right&#39;,
                code: 39
            },
            {
                type: &#39;down&#39;,
                code: 40
            },
            {
                type: &#39;left&#39;,
                code: 37
            },
            {
                type: &#39;up&#39;,
                code: 38
            }
        ]);

        return null;
    };

    /**
     * @private _keyDownHandler 自定义键盘事件分发
     * */
    KeyboardListener.prototype._keyDownHandler = function _keyDownHandler(e){
        var strCommand = this._keyCodeProcess(e);

        var objEvent = {
            type: &#39;&#39;,
            originEvent: e.originEvent
        };

        strCommand && this.callback[&#39;on&#39; + strCommand](objEvent);

        return null;
    };

    /**
     * @private _keyCodeProcess 处理按键码
     * */
    KeyboardListener.prototype._keyCodeProcess = function _keyCodeProcess(e){
        var code = e.keyCode + &#39;&#39;;
        var altKey = e.altKey;
        var ctrlKey = e.ctrlKey;
        var shiftKey = e.shiftKey;

        var threeKey = altKey && ctrlKey && shiftKey;
        var ctrlAlt = altKey && ctrlKey;
        var altShift = altKey && shiftKey;
        var ctrlShift = shiftKey && ctrlKey;

        var keyTypeSet = this.keyTypeSet;
        var resStr = &#39;&#39;;

        if(threeKey){
            resStr = keyTypeSet.threeKey[code];
        } else if(ctrlAlt) {
            resStr = keyTypeSet.ctrlAlt[code];
        } else if(ctrlShift) {
            resStr = keyTypeSet.ctrlShift[code];
        } else if(altShift) {
            resStr = keyTypeSet.altShift[code];
        } else if(altKey) {
            resStr = keyTypeSet.altKey[code];
        } else if(ctrlKey) {
            resStr = keyTypeSet.ctrlKey[code];
        } else if(shiftKey) {
            resStr = keyTypeSet.shiftKey[code];
        } else {
            resStr = keyTypeSet.singleKey[code];
        }

        return resStr
    };


    /**
     * @private _setKeyComposition 自定义键盘事件
     * @param {Object} config 键盘事件配置方案
     * @param {String} config.type 自定义事件类型
     * @param {keyCode} config.code 按键的码值
     * @param {Boolean} [config.ctrl] 是否与 Ctrl 形成组合键
     * @param {Boolean} [config.alt] 是否与 Alt 形成组合键
     * @param {Boolean} [config.shift] 是否与 Shift 形成组合键
     * */
    KeyboardListener.prototype._setKeyComposition = function _setKeyComposition(config){
        var altKey = config.alt;
        var ctrlKey = config.ctrl;
        var shiftKey = config.shift;

        var threeKey = altKey && ctrlKey && shiftKey;
        var ctrlAlt = altKey && ctrlKey;
        var altShift = altKey && shiftKey;
        var ctrlShift = shiftKey && ctrlKey;
        var code = config.code + &#39;&#39;;

        if(threeKey){
            this.keyTypeSet.threeKey[code] = config.type;
        } else if(ctrlAlt) {
            this.keyTypeSet.ctrlAlt[code] = config.type;
        } else if(ctrlShift) {
            this.keyTypeSet.ctrlShift[code] = config.type;
        } else if(altShift) {
            this.keyTypeSet.altShift[code] = config.type;
        } else if(altKey) {
            this.keyTypeSet.altKey[code] = config.type;
        } else if(ctrlKey) {
            this.keyTypeSet.ctrlKey[code] = config.type;
        } else if(shiftKey) {
            this.keyTypeSet.shiftKey[code] = config.type;
        } else {
            this.keyTypeSet.singleKey[code] = config.type;
        }

        return null;
    };

    /**
     * @method extendEventType 扩展键盘事件类型
     * @param {Object|Array<object>} config 键盘事件配置方案
     * @param {String} config.type 自定义事件类型
     * @param {keyCode} config.code 按键的码值
     * @param {Boolean} [config.ctrl] 是否与 Ctrl 形成组合键
     * @param {Boolean} [config.alt] 是否与 Alt 形成组合键
     * @param {Boolean} [config.shift] 是否与 Shift 形成组合键
     * */
    KeyboardListener.prototype.extendEventType = function extendEventType(config){
        var len = 0;
        if(config instanceof Array){
            len = config.length;
            while(len--){
                this._setKeyComposition(config[len]);
            }
        } else {
            this._setKeyComposition(config);
        }
        return this;
    };

    /**
     * @method bind 绑定自定义的键盘事件
     * @param {String} type 事件类型 如:['up', 'down', 'left', 'right', 'undo', 'redo', 'delete', zoomIn, 'zoomOut']
     * @param {Function} callback 回调函数,参数为一个自定义的仿事件对象
     * @param {String} description 对绑定事件的用途进行说明
     * */
    KeyboardListener.prototype.bind = function bind(type, callback, description){
        var allType = this.allEventType;
        if(allType.indexOf(type) === -1){
            throwError('不支持改事件类型,请先扩展该类型,或采用其他事件类型');
        }

        if(!(callback instanceof Function)){
            throwError('绑定的事件处理回调必须是函数类型');
        }

        this.callback['on' + type] = callback;

        this.eventDiscibeSet[type] = description || '没有该事件的描述';

        return this;
    };
    /**
     * @method unbind 解除事件绑定
     * @param {String} type 事件类型
     * */
    KeyboardListener.prototype.unbind = function unbind(type){
        this.callback['on' + type] = this._emptyEventHandler;

        return this;
    };
}();
Copy after login

[Related recommendations: jQuery video tutorial]

The above is the detailed content of Introduction to jQuery-based keyboard event listening control (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles