1.正在做app的项目,项目中有很多onclick事件,我有想法使用touch事件代替,因为有很多处需要做修改,在想能否简单的实现,在dom元素原型上绑定类似于onclick事件的实现。
如
变为
tap方法
function tap(ele, touchFn) {
var SupportsTouches = ("createTouch" in document),//判断是否支持触摸
StartEvent = SupportsTouches ? "touchstart" : "mousedown",//支持触摸式使用相应的事件替代
EndEvent = SupportsTouches ? "touchend" : "mouseup";
var startTime = null,
endTime = null;
ele.addEventListener(StartEvent, function (e) {
startTime = e.timeStamp
})
ele.addEventListener(EndEvent, function (e) {
endTime = e.timeStamp
// console.log(EndEvent+'间距='+(endTime-startTime))
if (endTime - startTime < 500) {
touchFn();
}
})
}
2.尝试了可以定义到原型上,非我所要
Object.prototype.tap1 = tap;
可以这样使用
var btn = document.getElementById('btn1');
tap1(btn, function() {
alert(1)
})
3.问,我如何绑定原型,设置公共的方法函数,可以使得在html中可以这样使用
更新- 2018.7.19
HTMLElement.prototype.ontap = function (fn) {
if (this.getAttribute("ontap")) {
var FnStr = this.getAttribute("ontap").split('(')[0];
console.log(FnStr);
}
var ele = this;
var SupportsTouches = ("createTouch" in document),//判断是否支持触摸
StartEvent = SupportsTouches ? "touchstart" : "mousedown",//支持触摸式使用相应的事件替代
EndEvent = SupportsTouches ? "touchend" : "mouseup";
var startTime = null,
endTime = null;
ele.addEventListener(StartEvent, function (e) {
startTime = e.timeStamp
})
ele.addEventListener(EndEvent, function (e) {
endTime = e.timeStamp
// console.log(EndEvent+'间距='+(endTime-startTime))
if (endTime - startTime < 500) {
fn();
}
})
};
document.querySelector('button').ontap(function () {
alert(1)
})