首页 > 学院 > 开发设计 > 正文

节点门面和自定义事件研究

2019-11-09 16:47:46
字体:
来源:转载
供稿:网友

借点击和轻触来研究节点门面和自定义事件

//初始版本function addTapListener(node, callback) { //start by supporting mousevents var startEvent = 'mousedown', endEvent = 'mouseup'; //if touch events are available use them instead if (typeof(window.ontouchstart) != 'undefined') { //touch events work startEvent = 'touchstart'; endEvent = 'touchend'; } node.addEventListener(startEvent, function(e) { var tap = document.createEvent('CustomEvent'); tap.initCustomEvent('tap', true, true, null); node.dispatchEvent(tap); }); node.addEventListener(endEvent, function(e) { var tapend = document.createEvent('CustomEvent'); tapend.initCustomEvent('tapend', true, true, null); node.dispatchEvent(tapend); }) node.addEventListener('tap', callback);}addTapListener(document.getElementById('toggle'), function(e){ e.PReventDefault(); e.target.className = 'active button'; togglePicture();});node.addEventListener('tapend', function(e){ e.preventDefault(); e.target.className = "button";});//优化版本 使用节点门面(function(){ var TOUCHSTART, TOUCHEND; //normal touch events if (typeof(window.ontouchstart) != 'undefined') { TOUCHSTART = 'touchstart'; TOUCHEND = 'touchend'; //microsoft touch events } else if (typeof(window.onmspointerdown) != 'undefined') { TOUCHSTART = 'MSPointerDown'; TOUCHEND = 'MSPointerUp'; } else { TOUCHSTART = 'mousedown'; TOUCHEND = 'mouseup'; } function NodeFacade(node){ this._node = node; } NodeFacade.prototype.getDomNode = function() { return this._node; } NodeFacade.prototype.on = function(evt, callback) { if (evt === 'tap') { this._node.addEventListener(TOUCHSTART, callback); } else if (evt === 'tapend') { this._node.addEventListener(TOUCHEND, callback); } else { this._node.addEventListener(evt, callback); } return this; } NodeFacade.prototype.off = function(evt, callback) { if (evt === 'tap') { this._node.removeEventListener(TOUCHSTART, callback); } else if (evt === 'tapend') { this._node.removeEventListener(TOUCHEND, callback); } else { this._node.removeEventListener(evt, callback); } return this; } window.$ = function(selector) { var node = document.querySelector(selector); if(node) { return new NodeFacade(node); } else { return null; } }})();$('.button').on('tap', function(e) { e.preventDefault(); togglePicture(); e.target.className = "active button";}).on('tapend', function(e) { e.target.className = "button";});
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表