跳转到带偏移的部分

时间:2018-02-26 10:51:29

标签: javascript jquery

我正在使用小的jQuery脚本滚动到id对应的部分,点击了标签的href。

例如,点击<a href="#section1">scroll to section1</a>用户窗口后,将转到带有id="section1"动画的目标部分。

使用标准设置一切正常,但在应用偏移后,动画会在滚动的最后阶段开始变得浑浊。

以下是在线代码的一部分: https://codepen.io/engray/pen/WMaXev

我尝试将偏移值更改为预定义值,但它根本没有帮助。你有什么想法,可能会导致动画跳跃效应吗?

2 个答案:

答案 0 :(得分:1)

由于导航栏已修复,您无需向headerHeight添加targetOffest

var targetOffest = target.offset().top  + headerHeight

仅使用target.offset().top作为参数应该有效。

注意:.animate() s scrollTop会将div的顶部滚动到页面顶部,您的代码会在您添加标题高度时滚动到导航栏的底部

$('a[href*="#"]').click(function(e){
  e.preventDefault();
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
  var targetOffest = target.offset().top;
  var headerHeight = document.getElementByClassName('navbar')[0].offsetHeight;
  $('html, body').animate({
      scrollTop: targetOffest
  }, 1000);
});
.navbar {
  position: fixed;
  display: flex;
  width: 100%;
  left: 0;
  right: 0;
  top: 0;
  z-index: 3;
  background: rgba(0,0,0,0.3);
}

.navbar ul li{
  display: inline-block;
}

.navbar ul li a{
  color: white;
}

.section{
  width: 100%;
  height: 100px;
}

#section1{
  background: red;
}

#section2{
  background: blue;
}

#section3{
  background: green;
}

#section4{
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="navbar">
  <ul>
    <li><a href="#section1">s1</a></li>
    <li><a href="#section2">s2</a></li>
    <li><a href="#section3">s3</a></li>
    <li><a href="#section4">s4</a></li>
  </ul>
</div>
<div class="section" id="section1"></div>
<div class="section" id="section2"></div>
<div class="section" id="section3"></div>
<div class="section" id="section4"></div>

编辑1:

设置属性tabindex后div会滚动到顶部,您可以使用.offset().scrollTo()再次设置滚动位置:

var x = $(window).offset().top,
    y = $(window).offset().left;
$target.attr('tabindex', '-1');
$target.focus();
$(window).scrollTo(x, y);

答案 1 :(得分:0)

由于:Jack Hair's answer at original css-tricks.com post,我设法修复了这种奇怪的行为。事实证明,最新的Chrome版本导致了焦点元素的问题

Peter说: 听起来像在Chrome的最新版本中,如果你有一个偏移(对于一个固定的导航栏),有一个错误会导致滚动跳转。

Jack Hair下面的解决方案:

// fix chrome of focus scroll
    $.fn.focusNoScroll = function() {
        var x = window.scrollX,
            y = window.scrollY;
        this.focus();
        window.scrollTo(x, y);
        return this;
    };