单页水平滚动锚点(jQuery)

时间:2017-08-27 22:09:21

标签: javascript jquery html css

我正在尝试创建页面的滚动水平部分。

这是一个非常简单的概念,之前我已经做了很多次,所以我必须错过一些相当明显的概念。

似乎它可以替代每次点击的正确偏移量。

$('a.scroll-trigger').click(function(e) {
  var $this = $(this);
  var $anchor = $($this.attr('href'));
  var $container = $($this.attr('data-container'));
  var offset = $anchor.offset().left;
  $container.scrollLeft(offset);
  e.preventDefault();
});
#pages {
  overflow-x: hidden;
  white-space: nowrap;
}

#pages>section {
  display: inline-block;
  width: 768px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li>
  <li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li>
  <li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li>
</ul>

<!-- pages is nested in a container with a maximum width of 768px. -->
<div id="pages">
  <section id="section1">
    <h2>Section 1</h2>
  </section>
  <section id="section2">
    <h2>Section 2</h2>
  </section>
  <section id="section3">
    <h2>Section 3</h2>
  </section>
</div>

它无法正常工作。 offset变量并不总是正确的。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这是你要找的吗?

&#13;
&#13;
$('.scroll-trigger').each(function(index){
  $(this).on('click',function(e) {
    var $this = $(this);
    var $anchor = $this.attr('href');
    var $container = $this.attr('data-container');
    var elem = $($anchor);
    var offset = (elem.offset().left - elem.offsetParent().offset().left); 

    if(offset >= 0){
      $($container).animate({'scrollLeft' : offset * index},200);
    }else{
      $($container).animate({'scrollLeft' : offset * -index},200);
    }
    e.preventDefault();
  });                      
})
&#13;
#pages{
  position: relative;
  overflow-x: hidden;
  white-space: nowrap;
  width: 100%;
  border:1px solid #565656;
}
#pages>section {
  display: inline-block;
  width: 100%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a class="scroll-trigger" href="#section1" data-container="#pages">Section 1</a></li>
  <li><a class="scroll-trigger" href="#section2" data-container="#pages">Section 2</a></li>
  <li><a class="scroll-trigger" href="#section3" data-container="#pages">Section 3</a></li>
</ul>

<!-- pages is nested in a container with a maximum width of 768px. -->
<div id="pages">
  <section id="section1">
    <h2>Section 1</h2>
  </section>
  <section id="section2">
    <h2>Section 2</h2>
  </section>
  <section id="section3">
    <h2>Section 3</h2>
  </section>
</div>
&#13;
&#13;
&#13;