【问题标题】:Smooth link scrolling not on whole body, but certain div平滑链接滚动不是在整个身体上,而是在某些 div 上
【发布时间】:2015-04-23 20:57:32
【问题描述】:

我正在使用此代码来平滑链接滚动:

    function filterPath(string) {
    return string
      .replace(/^\//,'')
      .replace(/(index|default).[a-zA-Z]{3,4}$/,'')  
      .replace(/\/$/,'');
    }

$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) == filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
  var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
  var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
   if ($target) {
        $(this).click(function() {
            var targetOffset = $target.offset().top;
            $('html, body, .container-1-2').animate({
                scrollTop: $target.offset().top - 70}, 600
             );

            return false;
        });
  }
}
});

滚动的不是整个页面,而是容器 1-2 类的特定 div。

我遇到的问题是,当单击锚链接时,它会滚动到指定的 id,但是当我再次单击相同的链接时,它会滚动到顶部。只是想不通如何防止再次滚动到顶部并保持静止。

【问题讨论】:

  • 尝试只为$(html, body)制作动画?乍一看,这就是全部。
  • 我试过了,滚动根本不起作用。
  • 你能显示 HTML 吗?更容易看到实时测试用例发生了什么。
  • link 这是链接。问题在于左侧的链接,称为 Specifications 和 Floorplan
  • 我知道可能是什么问题。使用offset() 是相对于页面的,用于“全局”导航。如果是嵌套元素,您可以尝试改用position()

标签: jquery html


【解决方案1】:

我找到了解决办法。

$(function() {
    $('a[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) {
            $('.content-container').animate({
                scrollTop: $('.content-container').scrollTop() + target.offset().top - 70
            }, 1000);
        return false;
        }
     }
   });
});  

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多