使用jQuery进行垂直滚动

使用jQuery进行垂直滚动,jquery,scroll,scrolltop,Jquery,Scroll,Scrolltop,我正在尝试实现垂直滚动。 单击“向下”分区时,将向上移动1个分区;单击“向上”分区时,将向下移动1个分区。 但它只在第一次点击时起作用。用户应该能够单击down直到最后一个div,然后应该禁用“down”div HTML: Javascript: $(document).ready(function(){ $('#down').live("click",function(){ var scrollval = $('.child').height(); $('

我正在尝试实现垂直滚动。 单击“向下”分区时,将向上移动1个分区;单击“向上”分区时,将向下移动1个分区。 但它只在第一次点击时起作用。用户应该能够单击down直到最后一个div,然后应该禁用“down”div

HTML:

Javascript:

$(document).ready(function(){    
   $('#down').live("click",function(){
      var scrollval = $('.child').height();
      $('#parent').scrollTop(scrollval);
   });

   $('#up').live("click",function(){
      var scrollval =  $('.child').height();
      $('#parent').scrollTop(-scrollval);
   });
});

jshiddle:

它只在第一次单击时起作用的原因是,您只从顶部移动+48px或-48px。您需要从当前scrollTop值中减去+/-48

因此,如果我们已经从顶部算起96px,我们按下向下键,我们想把48加到96,就像这样:

另外,请注意.live已经从jQuery1.7+贬值。如果您使用的是jQuery1.7,您需要使用.on,就像我的示例一样+

编辑-添加了显示/隐藏按钮功能 首先,你需要计算出一些变量。我在click事件之外声明了这些函数,以便在需要时可以在这两个函数中使用它们

// get the number of .child elements
var totalitems = $("#parent .child").length;
// get the height of .child
var scrollval = $('.child').height();
// work out the total height.
var totalheight = (totalitems*scrollval)-($("#parent").height());
向上:

向下:


谢谢非常感谢您的帮助,让它看起来如此简单!
$(document).ready(function(){    
   $('#down').live("click",function(){
      var scrollval = $('.child').height();
      $('#parent').scrollTop(scrollval);
   });

   $('#up').live("click",function(){
      var scrollval =  $('.child').height();
      $('#parent').scrollTop(-scrollval);
   });
});
 $(document).on("click", "#down", function(){
        var scrollval = $('.child').height();
        // this gives us the current scroll position
        var currentscrollval = $('#parent').scrollTop();

        $('#parent').scrollTop(scrollval+currentscrollval);
});
// get the number of .child elements
var totalitems = $("#parent .child").length;
// get the height of .child
var scrollval = $('.child').height();
// work out the total height.
var totalheight = (totalitems*scrollval)-($("#parent").height());
// hide/show buttons
if(currentscrollval == totalheight) {
     $(this).hide();         
 }
 else {
     $("#up").show();
 }
 // hide/show buttons
 if((scrollval+currentscrollval) == scrollval) {
    $(this).hide();         
 }
 else {
     $("#down").show();
 }