window.scroll页面加载不可靠

window.scrollTo unreliable on page load

本文关键字:加载 不可靠 scroll window      更新时间:2023-09-26

我有一个聚合物元素,它以人性化的格式显示时间戳。我希望时间戳的文本是一个永久链接,可以在页面加载时将浏览器滚动到元素。在shadow DOM中显然不支持常规HTML锚。这种解决方案有时有效,有时无效。我猜它的不可靠性与页面仍在加载有关,但我不知道如何修复它。我曾尝试将scrollTo命令放在ready()、DOMReady()和attached()中,但无论它在哪里,似乎都无法使其始终工作。我曾试过使用async()命令来延迟调用,但它仍然无法始终工作。请原谅我,这个例子不是一个可以工作的代码片段,但我不知道当它没有占据整个窗口时(比如在代码笔或其他东西中)如何使它工作。

<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>

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

它依赖于element.scrollIntoView(),并且类似于<core-doc-page>元素所做的事情。

<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>