Polymer scroll to a specific div

2019-08-14 07:17发布

问题:

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>