jQuery平滑滚动到元素 - 不能正常工作

时间:2017-09-03 02:39:35

标签: javascript jquery html

我试图制作一个"点击滚动"菜单在我的网站上(www.trianglesquad.com)。我尝试了一个代码  w3schools.com" https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll"。我正面临一个问题。它没有滚动到完美的点。例如,如果我点击"投资组合",它会滚动到投资组合部分的中间位置。它在3-4次点击后滚动到完美点。 任何帮助将受到高度赞赏:)

感谢。

1 个答案:

答案 0 :(得分:0)

不确定为什么所有下来的选票,因为我们都是在某个阶段的初学者...也许对于未来的帖子,尝试用一个例子创建一个JS小提琴并且更具体。

您可以通过添加或减去偏移量来更改滚动偏移量,如下例所示:

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top -200
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

这里的关键是这一行:

scrollTop: $(hash).offset().top -200

您可以添加或减去您选择的任意数量的像素。

编辑:

实际上尝试使用此代码:

$(document).ready(function() {

$("#xp-navigation").find("a[href*=#]:not([href=#])").click(function () {
        var offset = 0;
        var speed = 1000;
        var target = $(this.hash);

        $("html,body").animate({
            scrollTop: target.offset().top - offset
        }, speed);
    });

});

它更清洁,你也可以调整偏移量。

相关问题