Material Design Lite and jQuery, smooth scroll not working
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am unable to use .animate method of jQuery with Google's Material Design Lite(MDL). I have used MDL to make navigation bar, but smooth scrolling was not working.
Simple jQuery code is this:
$(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.offset().top; $("html, body").animate({scrollTop:position}, speed, "swing"); console.log("SMOOTH END"); }); });
And simple html code is this:
This code showed me the log, "SMOOTH BEGIN" and "SMOOTH END". However, that link worked as ordinary link, not like smooth. How can I get jQuery working with MDL? Maybe some conflicts are occurring, but console is not showing anything.
回答1:
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.
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