平滑链接滚动不在整个身体上,而是在某些div上 [英] Smooth link scrolling not on whole body, but certain div

查看:63
本文介绍了平滑链接滚动不在整个身体上,而是在某些div上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码进行平滑的链接滚动:

I'm using this code for smooth link scrolling:

    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;
        });
  }
}
});

不是滚动整个页面,而是滚动某些带有class container-1-2的div.

'm scrolling not the whole page, but only certain div with class container-1-2.

我遇到的问题是,单击锚链接时,它会滚动到指定的ID,但是当我再次单击同一链接时,它会滚动到顶部.只是无法弄清楚如何防止再次滚动到顶部并保持静止.

The problem I have is that when anchor link is clicked, it scrolls to the id which was specified, but when I click the same link again, it scrolls to the top. Just can't figure it out how to prevent scrolling it to the top again and stay still.

推荐答案

我找到了解决方案.

$(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;
        }
     }
   });
});  

这篇关于平滑链接滚动不在整个身体上,而是在某些div上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆