window.scroll页面加载不可靠
window.scrollTo unreliable on page load
我有一个聚合物元素,它以人性化的格式显示时间戳。我希望时间戳的文本是一个永久链接,可以在页面加载时将浏览器滚动到元素。在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>
相关文章:
- 如果数据为空,Ajax加载不会停止
- FileReader加载不在控制器范围Angular 2内
- requireJS 中的车把加载不成功
- 关闭-库加载不正确
- 弹出加载不起作用
- jQuery UI加载不正确?找不到对话框方法
- GULP中的Ctrl+S之后,实时重新加载不起作用
- 在解决Firebase GetRecord之前,视图加载不完整
- 网页加载不正确:'"JSON”;未定义'错误
- 加载不是来自“xampp的htdocs”或“root”文件夹的图像
- 阻止推特分享按钮加载不正确
- Durandal View偶尔加载不正确,而且总是在缩小时加载不正确
- 影子盒加载不起作用
- 传单显示悬停时的地图 - 地图加载不正确
- 余烬 CLI 实时重新加载不起作用
- 在Javascript中保存和加载不起作用
- 如何在 JSP 页面中编写 javascript 倒数计时器,以便重新加载不会重新启动计时器
- Fancybox2 无法加载.不需要冲突建议
- 重新加载不带 ssl 的页面(https 到 http)
- window.scroll页面加载不可靠