我有一个 polymer 元件,可以以人类友好的格式显示时间戳。我希望时间戳的文本成为一个永久链接,它将在页面加载时将浏览器滚动到该元素。 Shadow DOM 显然不支持常规 HTML anchor 。该解决方案有时有效,有时无效。我猜它的不可靠性与页面仍在加载有关,但我不知道如何修复它。我尝试将scrollTo 命令放入ready()、DOMReady() 和attached() 中,但无论它在哪里,似乎都无法使其一致工作。我尝试过使用 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>
最佳答案
这是一个包含所有 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>
关于javascript - window.scrollTo 页面加载不可靠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26639168/