window.scroll在页面加载时不可靠

时间:2014-10-29 19:40:01

标签: javascript polymer

我有一个聚合物元素,以人性化的格式显示时间戳。我希望时间戳的文本是一个永久链接,它将浏览器滚动到页面加载时的元素。在shadow DOM中显然不支持常规HTML锚点。这种解决方案有时可行,有时无效。我猜测它的不可靠性与页面加载的事实有关,但我无法弄清楚如何修复它。我已经尝试将scrollTo命令放在ready(),DOMReady()和attach()中,并且似乎无论它在哪里都能使它始终如一地工作。我已经尝试使用async()命令来延迟调用,但它仍然不能一致地工作。请原谅我这个例子不是一个正常工作的代码片段,但我不确定如何在它不占用整个窗口时(例如在codepen或其他东西中)使它工作。

<script src="http://www.polymer-project.org/platform.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">
<link rel="import" href="../../elements/momentjs.html">

<polymer-element name="time-ago" attributes="timestamp anchorId">
  <template>
    <a href="{{permalink}}" on-click="{{scrollToSelf}}" title="{{timestamp | unitToFullDateTime}}">{{timeAgo}}</a>
  </template>

  <script>
    Polymer('time-ago', {
      ready: function() {
        var self = this;
        var url = document.URL.replace(/#.*\/?$/, "");
        self.permalink = url + '#anchorid=' + encodeURIComponent(self.anchorId);
        var periodicUpdater = function () {
          self.timeAgo = moment.unix(self.timestamp / 1000.0).fromNow();
          self.async(function() {
            periodicUpdater();
          }, null, 10000);
        };
        periodicUpdater();
      },
      attached: function () {
        var self = this;
        var match = /#anchorid=(.*)$/.exec(document.URL);
        if (match) {
          var anchorId = match[1];
          if (anchorId === self.anchorId) {
            self.scrollToSelf();
          }
        }
      },
      scrollToSelf: function () {
        var self = this;
        window.scrollTo(0, self.offsetTop - 20);
      },
      unitToFullDateTime: function () {
        return moment.unix(arguments[0] / 1000.0).format('MMMM Do YYYY, h:mm:ss a');
      }
    });
  </script>
</polymer-element>

1 个答案:

答案 0 :(得分:1)

这是一个简化的解决方案,其中删除了所有moment.js逻辑,并使用要滚动到的元素的硬编码ID。您应该能够调整它以使用动态元素ID,但这在代码片段的上下文中并不能很好地工作。

它依赖element.scrollIntoView(),与<core-doc-page> element does类似。

<script src="//www.polymer-project.org/platform.js"></script>
<link rel="import" href="//www.polymer-project.org/components/polymer/polymer.html">

<polymer-element name="time-ago">
  <template>
    <div id="elementToScrollTo">
      <content></content>
    </div>
  </template>

  <script>
    Polymer({
      domReady: function() {
        this.$.elementToScrollTo.scrollIntoView();
      }
    });
  </script>
</polymer-element>

<div class="filler" style="height: 5000px;">Filler</div>
<time-ago>A long time ago!</time-ago>

相关问题