标签:class 创建 参数 触发事件 script page 自定义 获取 rip
移动端的事件类型和PC端的不同,有touchstart,touchmove,touchend...
今天,用了touchstart和touchend封装了一个左右上下滑动的触发事件(这里的封装就用到了订阅者发布模式)
步骤:一、创建事件(document.createEvent(“customEvent”))
二、初始化事件 (event.initCustomEvent("事件名称",true,true,{key:value}))
第二。第三个参数表示是否冒泡,是否取消,第四个参数是在时间触发时携带的额外的数据,它会保存在事件对象的detail属性中
三、分发事件 <---(发布者)
分发给需要的dom对象
四、DOM对象事件绑定 <---(订阅者)
思路:
在touchstart,也就是开始触摸时获取到坐标,将这些坐标值保存在一个对象字面量中,touchend阶段再获取一次坐标值保存到对象中
然后开始比较。
<div style="width:100%;height:600px;" id="box">我是内容</div>
<script>
var box = document.getElementById("box");
function swipe(obj){
var initCoord = { //初始化坐标
sx : 0, /*模*/
sy : 0, /*订阅者*/
ex : 0, /*式*/
ey : 0
}
//监听事件,获取开始位置坐标
obj.addEventListener("touchstart",function(e){
// console.info(e.targetTouches[0].pageX);
initCoord.sx = e.targetTouches[0].pageX;
initCoord.sy = e.targetTouches[0].pageY;
})
//结束地点坐标
obj.addEventListener("touchend",function(e){
initCoord.ex = e.changedTouches[0].pageX;
initCoord.ey = e.changedTouches[0].pageY;
//判断向左还是向右
if(initCoord.sx-initCoord.ex > 30){ //向左
//创建自定义事件
var event = document.createEvent("customEvent");
//初始化
event.initCustomEvent("swipeLeft",true,true,{data:"value"});
this.dispatchEvent(event);//事件分发 //发布消息 将时间分发到事件对象上了
// console.info("向左滑")
}
if(initCoord.ex - initCoord.sx >30){
var event = document.createEvent("customEvent");
//初始化
event.initCustomEvent("swipeRight",true,true,{data:"value"});
this.dispatchEvent(event);//
// console.info("向右滑")
}
if(initCoord.sy - initCoord.ey > 30){
var event = document.createEvent("customEvent");
event.initCustomEvent("swipeUp",true,true,{data:"value"});
this.dispatchEvent(event);
// console.info("向上滑")
}
if(initCoord.ey - initCoord.sy >30){
var event = document.createEvent("customEvent");
event.initCustomEvent("swipeDown",true,true,{data:"value"});
this.dispatchEvent(event);
// console.info("向下滑")
}
});
};
swipe(box);
box.addEventListener("swipeRight",function(e){
console.info("向右滑",e.detail.data,e)
})
</script>
标签:class 创建 参数 触发事件 script page 自定义 获取 rip
原文地址:http://www.cnblogs.com/lovelx256/p/6107066.html