简体   繁体   English

jQuery平滑滚动到div-奇怪的行为

[英]jquery smooth scroll to div - strange behaviour

I have a web page which has a fixed header, and 3 main divs one below the other. 我有一个网页,其中有一个固定的页眉,并且3个主要的div分别位于另一个的下面。 One of the links in the header is made to smooth scroll to the last div. 标头中的链接之一可以平滑滚动到最后一个div。 The scrolling works on first click, but when I click again, it scrolls to the top of page. 滚动在第一次单击时起作用,但是当我再次单击时,它将滚动到页面顶部。 So, basically it is behaving like a toggle. 因此,基本上它的行为类似于切换。 First click scrolls to div, next click scrolls to top of page. 第一次单击滚动到div,再单击一次滚动到页面顶部。

The code I have is: 我的代码是:

var targetOffset = $('#targetDiv').offset().top - 75;
$('html, body').animate({scrollTop: targetOffset}, 700);

The problem is you calculate the targetOffset on every click. 问题是您每次点击都会计算targetOffset Maybe this could work: 也许这可以工作:

$( document ).ready(function() {
  var targetOffset = $('#targetDiv').offset().top - 75;
  $('#theLink').click(function(){
    $('html, body').animate({scrollTop: targetOffset}, 700);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM