1

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

HTML:

<div id="up">up</div>
<div id="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
<div class="child">7</div>
<div class="child">8</div>
<div class="child">9</div>
<div class="child">10</div>
<div class="child">11</div>
</div>
<div id="down">down</div>

CSS:

#parent{
   width:300px;
   height:288px;
   border:1px solid #000;
   overflow:hidden;
}
.child{
   width:300px;
   height:48px;
   border:1px solid #FF0000;
}
#up{
   width:30px;
   height:20px;
   background-color:#006600;
   cursor:pointer;
}
#down{
   width:40px;
   height:20px;
   background-color:#006600;
   cursor:pointer;
}

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

jsfiddle:http: //jsfiddle.net/XGXvD/

4

1 回答 1

9

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

因此,如果我们已经距顶部 96px 并且我们按下,我们希望将 48 添加到 96,如下所示:

jsfiddle在这里

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

        $('#parent').scrollTop(scrollval+currentscrollval);
});

另外,请注意,.live()它已从 jQuery 1.7+ 开始贬值。您需要.on()像我的示例一样使用(如果您使用的是 jQuery 1.7+)

编辑 - 添加了显示/隐藏按钮功能

在这里更新了 jsfiddle

首先,您需要计算出一些变量。我在点击事件之外声明了这些,以便在需要时可以在这两个函数中使用它们。

// 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();
 }
于 2013-04-04T09:19:37.177 回答