1 . addEventListener方法用於給指定元素添加事件監聽器
// 第二個參數function是指定要事件觸發時執行的函數
element.addEventListener(event, function, useCapture)
2 . handleEvent 是實現Eventlistener的一種方式,如下
<script>
(function () {
// 作爲一個工具類出現
var utils = {};
// 添加事件方法
utils.addEvent = function (type, el, fn, capture) {
// 註冊事件監聽器,capture = true 事件句柄在捕獲階段執行,也就是立即執行
el.addEventListener(type, fn, !!capture);
};
// 刪除事件
utils.removeEvent = function (el, type, fn, capture) {
el.removeEventListener(type, fn, !!capture);
};
function Slidebar () {
this.sidebar = document.querySelector('.sidebar')
this.initEvent()
}
Slidebar.prototype = {
// 初始化事件
initEvent: function () {
utils.addEvent('touchstart', this.sidebar, this)
},
// 自動從傳入的對象中尋找handleEvent方法
handleEvent: function (e) {
// 事件類型
console.log(e.type)
// 根據事件類型,定義不同的處理函數
switch ( e.type ) {
case 'touchstart':
this._start(e);
break;
}
},
// touchstart事件處理函數
_start: function (e) {
}
}
// 實例化
new Slidebar()
})()
</script>