之前項目中的列表是采用的IScroll,但是在使用IScroll有一個問題就是:當內容不足全屏的時候,是木有辦法往下拉的,這樣就達不到刷新的目的了?!具@是本人工作中遇到的,具體例子具體分析,這里只作一個參考】
大致的例子是這樣的:
<style> * { margin: 0; padding: 0; } html,body,.container { width: 100%; height: 100%; } .container>ul>li { padding: 15px 20px; text-align: center; border-bottom: 1px solid #ccc; }</style><div id="container" class="container"> <ul class="scroller"> <li>item1</li> <li>item2</li> <li>item3</li> <li>item4</li> <li>item5</li> </ul></div><script src="https://cdn.bootcss.com/iScroll/5.2.0/iscroll.min.js"></script><script> var myScroll = null; function onLoad() { myScroll = new IScroll('container'); } window.addEventListener('DOMContentLoaded', onLoad, false);</script>那么,既然超過一屏是可以刷新的,那我們就來逛逛代碼吧。在github上搜索iscroll,打開第一個,找到src下面的core.js。
1. 思路
首先既然要下拉,肯定會觸發touchstart、touchmove以及touchend事件。搜索touchmove,很好,在_initEvents中的注冊了這個事件。
_initEvents: function (remove) { // ... // 這里省略若干代碼 if ( utils.hasTouch && !this.options.disableTouch ) { eventType(this.wrapper, 'touchstart', this); eventType(target, 'touchmove', this); eventType(target, 'touchcancel', this); eventType(target, 'touchend', this); } // ...},好吧,看到這里的時候,我表示懵了一下逼,這不就是個綁定事件么?this又是一個什么鬼,然后我去查了一下文檔,發現了這么一個東西。文檔地址
target.addEventListener(type, listener[, options]);target.addEventListener(type, listener[, useCapture]);target.addEventListener(type, listener[, useCapture, wantsUntrusted ]); // // Gecko/Mozilla onlylistener當所監聽的事件類型觸發時,會接收到一個事件通知(實現了 Event 接口的對象)對象。listener 必須是一個實現了 EventListener 接口的對象,或者是一個函數
木有看錯,listener是一個對象或者是一個函數。前提是這個對象實現了EventListener接口。我們接著往下看,發現了這么一個例子。
var Something = function(element) { // |this| is a newly created object this.name = 'Something Good'; this.handleEvent = function(event) { console.log(this.name); // 'Something Good', as this is bound to newly created object switch(event.type) { case 'click': // some code here... break; case 'dblclick': // some code here... break; } }; // Note that the listeners in this case are |this|, not this.handleEvent element.addEventListener('click', this, false); element.addEventListener('dblclick', this, false); // You can properly remove the listeners element.removeEventListener('click', this, false); element.removeEventListener('dblclick', this, false);}var s = new Something(document.body);
新聞熱點
疑難解答
圖片精選