聚合物滚动到特定div

时间:2016-02-09 21:46:58

标签: polymer polymer-1.0

我正在使用Polymer Starter Kit,但我需要的是当我点击一个元素(链接,buttom或类似)时,页面会滚动到同一页面中的特定<div>,就像你在使用方法:

<a href="specificID">并转到:<div id="specificID">

我怎样才能在聚合物中做到这一点?

2 个答案:

答案 0 :(得分:4)

在您的Polymer元素模板中,您应该有要滚动到的div。给你的div一些id。例如:<div id="icecream"></div>。 Polymer做了一件非常方便的事情,它将对所有模板节点的引用放在元素的$属性上。在元素的方法内部,您可以滚动到div,如下所示: this.$.icecream.scrollIntoView()。您可以通过将其注册为元素中其他元素的单击处理程序,或通过在元素上强制调用方法来触发此操作,例如: myElementInstance.someMethodThatCausesScrolling()

答案 1 :(得分:0)

我把这个剪切到了index.html的主体中,用于Polymer应用程序。当然,这是一个简单的登陆页面,我不介意将所有链接变成锚点,但它应该足够容易适应:

<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>
相关问题