javascript implementation of ecshop search box keyboard up and down key switch control

  • 2020-05-17 04:47:41
  • OfStack

In the createSelect() function, returns an object whose two methods next ()
And the moveSelect() call in prev () can be correctly pointed to the function, also can be put
Let's put moveSelect() outside.


/* Keyboard operation with recommended selection of questions */
    var curDo = null;
    var select = createSelect();
    $('#keywords').keyup(function(e){
        var theEvent =  e || window.event;
        code = theEvent.keyCode ? theEvent.keyCode : (theEvent.which ? theEvent.which : theEvent.charCode)
        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            BACKSPACE: 8,
            LEFT:37,
            RIGHT:39
        };
        clearTimeout(curDo);// The timer should be cancelled when the keyboard is played ajax Data acquisition operation
        switch(code) {
            case KEY.UP:
                select.next();
                break;
            case KEY.DOWN:
                select.prev();
                break;
            case KEY.RETURN:
                $('.suggest-hover').trigger('click');
                break;
            case KEY.LEFT:
                break;
            case KEY.RIGHT:
                break;
            default:
                curDo = setTimeout(getSuggest(),300);
                break;
        }
    });
/* suggest Select operation */
    function createSelect(){
        var CLASSES = {
            ACTIVE: "suggest-hover"
        };
        function moveSelect(step) {
            var listItems=$('.suggest-results li');
            // The current hover The number of
            var active;
            active =  $('.'+CLASSES.ACTIVE).index();
            listItems.eq(active).removeClass(CLASSES.ACTIVE);
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
            var activeItem = listItems.eq(active).addClass(CLASSES.ACTIVE);
        };
        return {
            next:function(){
                moveSelect(-1);
            },
            prev:function(){
                moveSelect(1);
            }
        };
    };

That's all I want to share with you. I hope you enjoy it


Related articles: