Material Design Lite and jQuery, smooth scroll not working

痴心易碎 提交于 2019-11-29 02:35:00

The reason you are not seeing anything happen is because you are scrolling on the body node. MDL handles the overflow within the mdl-layout__content, this is the element you should scroll on.

So this -

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

Now becomes-

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

Here's a codepen example - http://codepen.io/mdlhut/pen/BNeoVa

Mitsuhiko Shimomura helped me in a different stack-overflow question. Instead of var position = target.offset().top; I used var position = target.get( 0 ).offsetTop - 130; if not the scroll would go to top and throw off the position, it did not look good. I had to add - 130 to the .offsetTop because the smooth scroll was going past my target id's in the html. Thank you for the help! See my app where I used this smoothscroll feature.

And remember to add smooth class to anchors in html like this

<a class="smooth" href="#scrollToId">Target</a> 
<div id="scrollToId">Target</div>

$(function(){
  $('a.smooth').click(function(){
    console.log("SMOOTH BEGIN");
    var speed = 1000;
    var href= $(this).attr("href");
    var target = $(href == "#" || href == "" ? 'html' : href);
    var position = target.get( 0 ).offsetTop - 130;
    $(".mdl-layout__content").animate({scrollTop:position}, speed, "swing");
    console.log("SMOOTH END");
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!