Polymer scroll to a specific div

北战南征 提交于 2019-12-11 12:52:34

问题


I am using Polymer Starter Kit, but what I need is that when I click in an element (link, buttom or similar) the page makes a scroll to a specific <div> in the same page, like when you use:

<a href="specificID"> and goes to: <div id="specificID">

How can I do that in polymer?


回答1:


Inside of your Polymer element's template, you should have your div that you wish to scroll to. Give your div some kind of id. For example: <div id="icecream"></div>. Polymer does a very convenient thing, where it places references to all of your template nodes that have an id on the $ property of your element. Inside of a method on your element, you can scroll to your div as follows: this.$.icecream.scrollIntoView(). You can trigger this to happen by registering it as a click handler on another element in your element, or by imperatively calling your method on your element, e.g. myElementInstance.someMethodThatCausesScrolling()




回答2:


I threw this snipped into the body of index.html for a Polymer app. Granted this was a simple landing page where I didn't mind having all the links turn into anchors, but it should be adaptable easily enough:

<script>
  $(function() {
    $('a[href*="#"]:not([href="#"])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html, body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });
</script>


来源:https://stackoverflow.com/questions/35302820/polymer-scroll-to-a-specific-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!