首頁 >web前端 >js教程 >javascript實作ecshop搜尋框鍵盤上下鍵切換控制_javascript技巧

javascript實作ecshop搜尋框鍵盤上下鍵切換控制_javascript技巧

WBOY
WBOY原創
2016-05-16 16:08:441210瀏覽

在createSelect()函數中,傳回一個對象,這個對象的兩個方法next()
和prev()中的呼叫的moveSelect()能正確的指向到該函數,也可以把
moveSelect()函數放到外面來。

複製程式碼 程式碼如下:

/* 鍵盤操作與問題推薦選擇 */
    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);//鍵盤彈起的時候應取消定時ajax取得資料操作
        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選擇操作 */
    function createSelect(){
        var CLASSES = {
            ACTIVE: "suggest-hover"
        };
        function moveSelect(step) {
            var listItems=$('.suggest-results li');
            //目前hover的步數
            var active;
            active =  $('.' CLASSES.ACTIVE).index();
            listItems.eq(active).removeClass(CLASSES.ACTIVE);
            active = step;
            if (active                 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);
            }
        };
    };

以上就是本文分享給大家的全部內容了,希望大家能夠喜歡

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn