Polymer 2.0中iron-scroll-threshold绑定document滚动时阈值事件不触发
解决Polymer 2.0中iron-scroll-threshold的lower-threshold事件不触发问题
我一眼就发现问题所在了——你给iron-scroll-threshold加了display: none;的样式!这个设置会让元素完全从文档流中消失,它根本没法监听页面的滚动状态,自然也就触发不了lower-threshold事件了。
修复步骤:
- 移除/替换
display: none;样式
直接删掉<style>里的iron-scroll-threshold { display: none; }就行;如果不想让这个元素影响页面布局,可以用不破坏元素功能的隐藏方式,比如绝对定位把它移出可视区域:
这样元素依然存在于DOM中,能正常监听滚动事件。iron-scroll-threshold { position: absolute; top: -9999px; left: -9999px; }
修正后的完整代码示例:
<link rel="import" href="../../bower_components/polymer/polymer-element.html"> <link rel="import" href="../../bower_components/iron-scroll-threshold/iron-scroll-threshold.html"> <dom-module id="documentscroll-app"> <template> <style> :host { display: block; } /* 用绝对定位隐藏元素但保留滚动监听功能 */ iron-scroll-threshold { position: absolute; top: -9999px; left: -9999px; } </style> <h2>Hello [[prop1]]!</h2> <!-- scroll-target uses the document scroll --> <iron-scroll-threshold id="scrollThreshold" scroll-target="document" lower-threshold="500" on-lower-threshold="loadMoreData"> </iron-scroll-threshold> <!-- 保留足够多的内容让页面出现滚动条 --> <h4> XXXXXXX MORE LINES TILL SCROLL IS VISIBLE </h4> <h4> XXXXXXX MORE LINES TILL SCROLL IS VISIBLE </h4> <h4> XXXXXXX MORE LINES TILL SCROLL IS VISIBLE </h4> <!-- 可重复添加更多行确保滚动条出现 --> </template> <script> /** * @customElement * @polymer */ class DocumentscrollApp extends Polymer.Element { static get is() { return 'documentscroll-app'; } constructor() { console.log("Constructor getting called "); super(); } // End of constructor static get properties() { return { prop1: { type: String, value: 'documentscroll-app' } }; } loadMoreData () { console.log("Loading more data"); this.$.scrollThreshold.clearTriggers(); } ready () { console.log("Scroll object is READY"); super.ready(); this.addEventListener('click', this._onClick); } _onClick(event) { console.log("Click getting called"); } } window.customElements.define(DocumentscrollApp.is, DocumentscrollApp); </script> </dom-module>
额外检查点:
- 确认页面内容确实足够长,滚动到距离底部500px的位置(也就是你设置的
lower-threshold值)时,能触发事件; - 确保你安装的
iron-scroll-threshold版本与Polymer 2.0兼容(bower安装的版本应为2.x系列); - 可以在
ready方法里打印this.$.scrollThreshold,确认元素实例已正确获取。
这样修改后,loadMoreData应该就能正常触发了!
内容的提问来源于stack exchange,提问作者Sachin Naik
相关产品推荐
相关产品推荐

