左侧和右侧的keydown jquery模态图像

时间:2016-05-20 12:44:25

标签: javascript jquery html

我需要用键盘导航我的模态图像,但我不知道改变上一个和下一个图像的jquery动作,这是我的JS:

$(document).ready(function () {
    $('.container img').click(function () {
        var src = $(this).attr('src');
        $('.modal').css({
            display: "block"
          });
        $('.modal-content').attr("src", src);
        $(this).keydown(function (e) {
          if (e.keyCode == 37) { //move left
              //change to prev image  
          } else if (e.keyCode == 39) {  //move right
              //change to next image  
          }
          });
        });
    });
});

我的html是:

<div class="container">
    <img src="img/bg1.jpg" alt=""/>
    <!-- The Modal -->
    <div class="modal">
        <span class="close">×</span>
        <img src="" class="modal-content" alt="">
    </div>
    <img src="img/bg2.jpg" alt=""/>
    <!-- The Modal -->
    <div class="modal">
        <span class="close">×</span>
        <img src="" class="modal-content" alt="">
    </div>
</div>

我认为我需要jquery索引来索引我的图像,但是如何执行呢? 还是有另一种方法? 小提琴here
感谢

1 个答案:

答案 0 :(得分:0)

基本上,您需要将keydown eventwindow绑定,并将当前打开的图像对象存储在全局变量中。

试试这个

updated jsfiddle

<强> HTML

    <div class="container">
      <img src="http://placekitten.com/200/300" alt="" />
      <img src="http://placekitten.com/200/287" alt="" />
    </div>
    <!-- The Modal -->
    <div class="modal">
      <span class="close">×</span>
      <img src="" class="modal-content" alt="">
    </div>

<强>的Javascript

    $(document).ready(function() {
      var $thisImage;
      $('.container img').click(function() {
        $thisImage = $(this);
        var src = $thisImage.attr('src');
        $('.modal').css({display: "block"});
        $('.modal-content').attr("src", src);    
      });
      $(window).keydown(function(e) {
          if (e.keyCode == 37) { //move left
            if($thisImage.prev().is('img')){
              var prev = $thisImage.prev().attr('src');
              $thisImage = $thisImage.prev();
              $('.modal-content').attr("src", prev);    
            }
          } 
          else if (e.keyCode == 39) { //move right
            if($thisImage.next().is('img')){
              var next = $thisImage.next().attr('src');
              $thisImage = $thisImage.next();
              $('.modal-content').attr("src", next);    
            }  
          }
        });
      $('.close').click(function() {
        $('.modal').css({
          display: "none"
        });
      });
    });