jquery animation.scrollTop()在mdl链接中不起作用

jquery animate.scrollTop() not working in mdl links

本文关键字:mdl 链接 不起作用 animation scrollTop jquery      更新时间:2023-09-26

大家好,我正试图用谷歌mdl制作一个网站模板,但问题是点击菜单链接时将页面滚动到相应部分的代码不起作用。

请参阅代码以获得帮助:

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');
    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }
    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();
    // top position relative to the document
    var pos = $(id).offset().top - 10;
    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});
.Home-section {
  height:500px;
  background: deepskyblue;
  width:100%;
  }
.About-section {
  height:300px;
  background:deeppink;
  width=100%;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<head>
    
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.min.css">
  <script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
    <link rel="stylesheet" href="js/lightbox2-master/src/css/lightbox.css">
    <link rel="stylesheet" href="http://anijs.github.io/lib/anicollection/anicollection.css">
    <link rel="stylesheet" href="js/animate.css">
    <link rel="stylesheet" href="main.css">
    
</head>
<body>
  <div class="mdl-layout mdl-js-layout">
<div class="mdl-layout__content">
  <a href="#home" class="mdl-navigation__link">Home</a>
  <a href="#about" class="mdl-navigation__link">About</a>
       
  <div class="Home-section" id="home"></div>
  <div class="About-section" id="about"></div>
  
  
  </div>
    </div>
</body>
  

所以,如果你知道这个问题的解决方案,请告诉我。

任何可以使用mdl的插件也可以为我做这项工作。

提前感谢

如果它没有在谷歌mdl上滚动,则可能您没有在htmlbody上滚动。查看这篇文章了解更多细节:Material Design Lite和jQuery,平滑滚动不起作用

所以这段代码:

$('body, html').animate({scrollTop: pos});

应该是这样的:

$('mdl-yout').animate({scrollTop:pos});

我知道这是一篇迟发的帖子,但不管怎样。

我找到了答案。它并不完美,但它有效。

而不是

$('body, html').animate({scrollTop: pos});

使用

$(".mdl-layout__content").animate({scrollTop: pos});

您没有看到任何事情发生的原因是因为您在主体节点上滚动。MDL处理MDL-layout__content中的溢出,这是您应该滚动的元素。

因此:

$("html, body").animate({scrollTop:position}, speed, "swing");

现在变成:

$(".mdl-layout__content").stop().animate({scrollTop:position}, speed, "swing");