对单击和键下(向左和向右)箭头键执行操作



我有一个仪表板页面,有一个左窗格滑动点击。我想让同样的事情发生在按左箭头和右箭头键。

有谁能帮我一下吗?我可以一键完成。下面是我的解决方案:

$(document).ready(function() {
      $('#opener, .left-panel-head').on('click', function() {
        var panel = $('#LeftPanel');
        if (panel.hasClass("visible")) {
          panel.removeClass('visible').animate({'margin-left': '-300px'});         
					$('#rightPanel').animate({'width': '100%'});
        } else {
          panel.addClass('visible').animate({'margin-left': '0px'});         
					$('#rightPanel').animate({'width': '74%'});
        }
        return false;
      });
  });

function updatePanel(direction) {
    if(direction === 'left') {
         // pressing left
    }else if(direction === 'right') {
         // pressing right
    }
};
 $(document).keypress(function( event ) {
      if(event.which == 37) {
         updatePanel('left');
      }else if(event.which == 39) {
         updatePanel('right');
      }
    };
 $('#opener, .left-panel-head').on('click', updatePanel('left'));
 $('#opener, .right-panel-head').on('click', updatePanel('right'));

你可以让你的函数成为一个实际的函数,而不是一个传递给点击事件的匿名函数,然后从多个地方调用它。

(function($, document){
    var $document = $(document);
    //shared function
    function stuff(){
    }
    //check if key pressed was one of the left or right arrows
    function checkKey(e){
        var c = e.which ? e.which : e.keyCode;
        //left arrow, right arrow
        if(c === 37 || c === 39){
            //call stuff if left or right arrow was pressed
            stuff();
        }
    }
    //call stuff on click
    $('#opener, .left-panel-head').on('click', stuff);
    $document.on('keydown', checkKey);
})(jQuery, document);

最新更新