对click和keydown(左和右)箭头键执行操作

时间:2015-07-22 22:15:46

标签: javascript jquery

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

有人可以帮我这个吗?我可以点击它。以下是我的解决方案:



$(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;
      });
  });




2 个答案:

答案 0 :(得分:1)

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'));

答案 1 :(得分:0)

您可以将您的函数设置为实际函数,而不是传递给Click事件的anon函数,然后从多个位置调用它。

(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);