jquery - 使用 jQuery、scrollTop 和 #anchors 锁定奇怪的浏览器窗口

标签 jquery html css

使用 scrollTop 导航到 anchor 时,我在多个浏览器中遇到了一个奇怪的问题。窗口正确滚动,但以一种难以破解的方式被锁定。这是 Safari 中问题的视频,但同样的事情也发生在 Chrome 中:

http://www.screencast.com/t/vyM16IlVb

请注意浏览器窗口如何对抗滚动,无论我是轻轻滚动还是猛烈滚动。它最终会崩溃,但我不知道是什么让它成为可能。

我正在使用一个 jQuery 函数来实现我在 Web 上找到的平滑滚动 anchor 链接。它滚动得很好,一般来说,除此之外。这是该脚本:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

任何关于这可能是什么的想法都将不胜感激。提前致谢!

最佳答案

似乎 animate 仍在尝试到达其目标滚动位置。 jQuery 计算相对于当前滚动位置的 offset().top,此时滚动位置是屏幕之外的位置,或者为负数。因此,当您排队动画以达到负滚动位置时,它永远不会到达它。

在触发动画之前尝试一个简单的检查并防止负目标。

 var top = target.offset().top;

 $('html,body').animate({
     scrollTop: top < 0 ? 0 : top
 }, 1000);

但是如果页面已经滚动,这将不会滚动到您想要的位置,要解决这个问题,请考虑像这样的当前滚动位置:

var top = target.offset().top + $(window).scrollTop();

 $('html,body').animate({
     scrollTop: top // top should never be negative this way
 }, 1000);

关于jquery - 使用 jQuery、scrollTop 和 #anchors 锁定奇怪的浏览器窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27286075/

相关文章:

jquery - Knockout.js Jquery跑马灯功能

CSS重叠标签不同宽度

css - 字体在 Windows 中看起来失真

CSS - 如何让子元素 float 超过其父元素宽度

javascript - 未捕获类型错误: Cannot set property 'onClick' of null

jquery - 使用 jquery 在堆叠的 div 之间拖动水平条

javascript - 如何在 JQuery 中解析集合

java - jQuery Ajax文件上传:org. springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数 'upload'不存在

jquery - 单击 anchor 链接时淡入/淡出音乐

javascript - 从使用 JavaScript 创建的按钮获取 ID