在另一页平滑滚动到锚点

3
在查看论坛和指南后,我找到了一种解决平滑滚动问题的方法。但在尝试之前,我想请教一些热心人士,下面的解决方案是否适用于我,或者我是否遗漏了重要的内容。
我正在处理一个现场网站,我不想引起问题或破坏任何东西,所以在添加以下代码之前,我想先确认一下。我也对Java或编码一无所知,请原谅我如果我没有使用正确的术语。
我想启用平滑滚动到另一个页面上的锚点。 例如,从我的主页“domain.com/home”点击链接,然后 加载新页面,例如“domain.com/contact” 并在加载新页面时,平滑地滚动到锚点“domain.com/contact#section1”。
目前,它只是跳转,我想知道下面的步骤是否可以实现平滑滚动。
我计划进行以下操作:
  1. Add the following codes to the website template's '' section (in the Joomla admin panel):

    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"> 
    </script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    
我不确定是否需要这样做,因为我已经使用了一些组件的 jQuery,重新加载 jQuery 是否是不必要的呢?或者无论如何添加此代码都不会有害吗?
  1. Then add this code to the same section in the template:

    <script type="text/javascript" >
    $('html').css({
    display: 'none'
    });
    
    $(document).ready(function() {
    var hashURL = location.hash;
    if (hashURL != "" && hashURL.length > 1) {
    $(window).scrollTop(0);
    $('html').css({
      display: 'block'
    });
    smoothScrollTo(hashURL);
    } else {
    $('html').css({
      display: 'block'
    });
    }
    });
    
    function smoothScrollTo(anchor) {
    var duration = 5000; //time
    var targetY = $(anchor).offset().top;
    $("html, body").animate({
    "scrollTop": targetY
    }, duration, 'easeInOutCubic');
    } 
    </script>
    
  2. As far as I know, this will enable the smooth scrolling, but I haven't added anything like 'smoothscroll.js' (which I've read a lot about) -- will that also need adding in the '' (after I upload it to the server), or is that included in the jQuery library?

如果这个问题看起来很幼稚,我向您道歉,因为我是边学习边做的。非常感谢提供反馈的每一个人,我真心感激您的时间和耐心。

最好的祝福, Ben

1个回答

1
首先,Joomla已经加载了jQuery,因此您不需要再次加载它。我建议使用Joomla扩展(这里有一个免费的),或者使用平滑滚动库(像这个)。假设您选择后者,您只需要在Joomla模板中放置链接到JS文件并初始化它(这在Github项目页面上都有解释)。
这两个选项都很简单,但如果您没有太多编程经验,那么扩展可能是最好的选择。
编辑:要在GitHub库上使用smoothscroll进行页面加载,您需要将最后一个函数更改为:
function smoothScrollTo(anchor) {
    var scroll = new SmoothScroll();
    scroll.animateScroll(anchor);
}

1
谢谢你,杰克。我尝试了你提到的第一个插件,但是没有成功,甚至不能在同一页上进行平滑滚动。我的问题是,如果我安装第二个平滑滚动实现(来自Github),我在原始帖子中键入的代码是否足以使锚点在其他页面上也能正常工作? - Ben Goldie
它应该可以工作,但我已经编辑了问题,以便提供您需要使用的函数,如果您想利用GitHub库。在第三行,您还可以指定一个额外的参数来控制动画类型(有关此信息,请参阅项目页面)。 - Jake Dickerson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接