按“j”</div>时滚动到下一个<div>

时间:2014-11-30 20:45:54

标签: javascript jquery html

我想你们都在facebook上看过这个功能。当您按j时,滚动位置会跳到下一个故事,当您按下k时,它会滚动到上一个故事。

现在,如果我有很多类.story的div(在片段中它们都具有相同的高度;但实际上,它们会有所不同),我如何浏览它们(滚动通过在Facebook上按.storyj来预测下一个和上一个k

body{  
  background-color:#ecf0f1;
}

.story
{
  background-color: #fff;
  border-radius: 5px;
  height: 500px;
  margin: 20px auto;
  width: 70%;
}
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>
<div class="story">
  
</div>

2 个答案:

答案 0 :(得分:4)

&#13;
&#13;
$(document).keypress(function(e){
  var forward;
  if (e.keyCode == 106) {
    forward = true;
  } else if (e.keyCode == 107) {
    forward = false;
  } else {
    return true;
  }
  
  if (!$(".story.current").length) {
    $(".story:first").addClass("current");
  }
  
  if ($(".story.current").length) {
    var current = $(".story.current");
    var next;
    if (forward) {
      next = current.next(".story")
    } else {
      next = current.prev(".story");
    }
    if (next.length) {
      current.removeClass("current");
      next.addClass("current");
    } else {
      alert("nope.");
    }
  }
  
  $("html, body").animate({ scrollTop: $(".current").offset().top }, 100);
});
&#13;
body{  
  background-color:#ecf0f1;
}

.story
{
  background-color: #fff;
  border-radius: 5px;
  height: 500px;
  margin: 20px auto;
  width: 70%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="story">
  a
</div>
<div class="story">
  b
</div>
<div class="story">
  c
</div>
<div class="story">
  d
</div>
<div class="story">
  e
</div>
<div class="story">
  f
</div>
<div class="story">
  g
</div>
<div class="story">
  h
</div>
<div class="story">
  i
</div>
<div class="story">
  j
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我将再添加一个解决方案,在我看来更简单一点:

var $story = $('.story');

$(document).keyup(function(e) {
    var index;

    if (e.keyCode == 74) {
        index = $story.filter('.focused').index() + 1;
    }
    else if (e.keyCode == 75) {
        index = $story.filter('.focused').index() - 1;
    }

    if (index < $story.length && index >= 0) {
        $story.removeClass('focused').eq(index).addClass('focused');   
    }

    $("html, body").animate({ 
        scrollTop: $focused.offset().top 
    }, 200);
});

演示:http://jsfiddle.net/vfw15v7d/