Navigate the UI using only keyboard

后端 未结 5 1633
故里飘歌
故里飘歌 2020-12-31 15:21

I\'m trying to navigate thru a list of records using only keyboard. When the page loads, the default \"focus\" should be on the first record, when the user clicks the down a

5条回答
  •  感动是毒
    2020-12-31 15:55

    I had a similar requirement to support UI navigation using arrow keys. What I finally came up with is DOM's keydown event handler encapsulated within an AngularJS directive:

    HTML:

    • {{ record.name }}

    CSS:

    .record {
        color: #000;
        background-color: #fff;
    }
    .record:focus {
        color: #fff;
        background-color: #000;
        outline: none;
    }
    

    JS:

    module.directive('focusable', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.attr('tabindex', '-1'); // make it focusable
    
                var tag = attrs.tag ? scope.$eval(attrs.tag) : undefined; // get payload if defined
                var onKeyHandler = attrs.onKey ? scope.$eval(attrs.onKey) : undefined;
    
                element.bind('keydown', function (event) {
                    var target = event.target;
                    var key = event.which;
    
                    if (isArrowKey(key)) {
                        var nextFocused = getNextElement(key); // determine next element that should get focused
                        if (nextFocused) {
                            nextFocused.focus();
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    }
                    else if (onKeyHandler) {
                        var keyHandled = scope.$apply(function () {
                            return onKeyHandler.call(target, key, tag);
                        });
    
                        if (keyHandled) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    }
                });
            }
        };
    });
    
    function MainCtrl ($scope, $element) {
        $scope.onKeyPressed = function (key, record) {
            if (isSelectionKey(key)) {
                process(record);
                return true;
            }
            return false;
        };
    
        $element.children[0].focus(); // focus first record
    }
    

提交回复
热议问题