jquery - 滚动按钮滚动到多个元素位置

标签 jquery html

我想创建一个滚动到 jquery 中多个元素位置的按钮。

假设我有这段代码:

<div class="container">
  <div>This is div one.</div>
  <div>This is div two.</div>
  <div>This is div three.</div>
  <div>This is div four.</div>
  <div>This is div five.</div>
</div>

我可以在 jquery 中创建一个事件,如下所示:

$('button#divone').click(function(){
  $('body').scrollTop(/*Element pos*/);
});

但是,这意味着我必须为每个 div 创建一个按钮,并为每个 div 创建一个 jquery 事件。

还有什么更好的办法吗?

最佳答案

试试这个:

$(document).ready(function(){

  var scrolled = 1;
  /*If you want it to start from the first div set the value to 0;*/
  
  var elements = $('div.container').find('div').length;
  
  /*Scroll Down button*/
  $('button#scrollbtn_D').click(function(){
    
    var pos = $('div.container div').eq(scrolled).offset().top;
      
    $('html,body').animate({
      scrollTop: pos},
    'slow');
      
    scrolled += 1;
    
    if(scrolled>=elements){
      $(this).hide();
    }
    
    $('button#scrollbtn_U').show();
  
  });
  
  /*Scroll Up button*/
  $('button#scrollbtn_U').click(function(){
    scrolled -= 2;
    var pos = $('div.container div').eq(scrolled).offset().top;

    $('html,body').animate({
      scrollTop: pos},
    'slow');
    
    scrolled += 1;
    
    if(scrolled==1){
      $(this).hide();
    }
    
    $('button#scrollbtn_D').show();
  
  });
  
  $('button#scrollbtn_U').hide();
  
});
div.container{
  width: 300px;
  height: auto;
  position: relative;
  padding: 10px;
  border: 1px solid rgba(0,0,0,0.1);
}
div.container div{
  width: 100%;
  height: 300px;
  text-align: center;
}
button#scrollbtn_D{
  width:50px;
  height:50px;
  position: fixed;
  top: 8px;
  left:340px;
  cursor: pointer;
}
button#scrollbtn_U{
  width:50px;
  height:50px;
  position: fixed;
  top: 8px;
  left:395px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">

  <div>This is div one.</div>
  <div>This is div two.</div>
  <div>This is div three.</div>
  <div>This is div four.</div>
  <div>This is div five.</div>

</div>
<button id="scrollbtn_D">Down</button>
<button id="scrollbtn_U">Up</button>

关于jquery - 滚动按钮滚动到多个元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51572562/

相关文章:

html - CSS - 垂直时间轴,连接到点

jquery - Symfony2 表单通过 JQuery AJAX 传递 CSRF

c# - 如何将jquery添加到asp.net页面并格式化gridview列

jquery - 在移动 View 中,我们希望显示每个 div 的 div 底部

javascript - 如何循环使用highcharts制作多个图表?

javascript - 如何使背景图像位置在所有分辨率下保持相同?

javascript - 无法让 Disqus 在单页应用程序中正常工作

javascript - 使用 JQuery 评分星级并将数据提交给分析

javascript - 如何使用jquery注入(inject)带有 Angular Directive(指令)的html元素?

html - li::before 中图像前不需要的空间