移动端touch和click事件都触发
2016/09/23    标签: mobile    touch    click   

因为移动端android支持touch和click事件,苹果手机只支持touch事件,PC端只支持click事件;

为了让一个方法在三种环境下只执行一次。现想到如下解决方案:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
<div id="nihao" style='height:1000px;'>

ffffffffffffffffffffffff<br/>
ffffffffffffffffffffffff<br/>
ffffffffffffffffffffffff<br/>
ffffffffffffffffffffffff<br/>
</div>

</body>
<script type="text/javascript">
var __=function(domObj){
    domObj.click=function(fun){
        //高位触屏点击,地位鼠标点击
        var flagMove='00';
        domObj.addEventListener('touchstart', function(event){
            flagMove='01';
        })
        domObj.addEventListener('touchmove', function(event){
            flagMove='11';
        })
        domObj.addEventListener('touchend',function(event){
            if(flagMove!='11'){
                fun.call(this,event);
            }
                flagMove='01';
        })
        domObj.addEventListener('click', function(event){
            if(flagMove=='00'){
                fun.call(this,event);
            }
        });
        return __(domObj);
    }
    return domObj;
}
//使用方法
var i=1;
__(document.getElementById('nihao')).click(function(event){
    i++;
    console.log(this);
    document.getElementById('nihao').innerHTML=document.getElementById('nihao').innerHTML+i+'<br/>';
}).click(function(){
    alert(2);
});
</script>
</html>