jQuery滚动到另一个页面上的部分

时间:2021-05-30 15:09:02

标签: javascript html jquery

我有一个网站,它使用 jQuery 在几个部分之间滚动(在 page1.html 中)。现在,我向网站添加了另一个页面(page2.html)。

我希望 page2.html 标题中的链接链接回 page1.html 中的相应部分。

在 page2.html 中我写道:

  <li><a href="page1.html#splash">Home</a></li>

此链接回 page1.html#splash。但是在第 1 页上,该站点不会滚动到相应的部分。

我的 JavaScript 是:

$(document).ready(function(){

$('a[href=\\#]').click(function(e){
    e.preventDefault();
    $('nav').removeClass('visible');
    $('html,body').stop().animate({scrollTop: $('.'+$(this).data('scrollto')).offset().top-65 }, 700, 'easeInOutExpo', function(){});
});

我已经尝试过的:

我尝试将以下代码添加到 page1.html:

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

    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      var hash = this.hash;

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

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

但是没有滚动到右侧部分,控制台显示以下错误:index.html:19 Uncaught ReferenceError: $ is not defined

坦率地说,由于缺乏该领域的专业知识,我陷入了困境。

当来自另一个页面时,我如何管理网站实际上滚动到正确的部分?

2 个答案:

答案 0 :(得分:0)

一旦离开页面,上一页的 JavaScript 就无法控制它。因此,您需要在新页面加载时使用 jQuery 来处理它。将此代码放在 page1.html 上,将注释更改为滚动命令:

$(document).ready(function() {
    if (window.location.href.includes('#splash')) {
        let animationTime = 100;
        $('html, body').animate({
            scrollTop: $('.splash').offset().top
        }, animationTime);
    }
});

答案 1 :(得分:0)

Uncaught ReferenceError: $ is not defined 

当您的页面未获得 JQuery

时会出现此类错误