键盘上下键

原生js

var op = -1;
document.onkeyup = function (event) {
  var e = event || window.event || arguments.callee.caller.arguments[0];
  //  arguments.callee.caller.arguments[0];???????
  var headerSearechZheng = document.getElementById("header-search-zheng");
  // var i=0;
  if (headerSearechZheng.innerHTML != "") {
    switch (e.keyCode) {
      case 40:
        op++;
        if (op > headerSearechZheng.children.length - 1) {
          op = headerSearechZheng.children.length - 1;
        }
        for (let i = 0; i < headerSearechZheng.children.length; i++) {
          headerSearechZheng.children[i].className = "";
        }
        headerSearechZheng.children[op].className = "active";

        console.log(op);
        break;
      case 38:
        op--;
        if (op < 0) {
          op = 0;
        }
        console.log(op);
        for (let i = 0; i < headerSearechZheng.children.length; i++) {
          headerSearechZheng.children[i].className = "";
        }
        headerSearechZheng.children[op].className = "active";
        break;
      default:
        break;
    }
  }
};

jQuery

var op = -1;
    $('.header-search-input').on('keyup', function (event) {
        var e = event || window.event;
        var headerSearchZheng = $('#header-search-zheng');
        if (headerSearchZheng.html() != null) {
            switch (e.keyCode) {
                case 40:
                    op++;
                    if (op > headerSearchZheng.children().length - 1) {
                        op = headerSearchZheng.children().length - 1;
                    }
                    headerSearchZheng.children().eq(op).addClass('active').siblings().removeClass('active');
                    console.log(op);
                    break;
                case 38:
                    op--;
                    if (op < 0) {
                        op = 0;
                    }
                    headerSearchZheng.children().eq(op).addClass('active').siblings().removeClass('active');
                    break;
                default:
                    break;
            }
        }
    });
    // 鼠标事件
    $('#header-search-zheng').on('mouseenter','li',function(event){
        $('#header-search-zheng li').eq($(this).index()).addClass('active').siblings().removeClass('active');
        op=$(this).index();
    })

 

你可能感兴趣的:(html,javascript)