JS 优化移动端 active 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<ol>
<li class="bg1">111111111111</li>
<li class="bg2">222222222222</li>
<li class="bg3">333333333333</li>
<li class="bg4">444444444444</li>
<li class="bg5">555555555555</li>
</ol>
<hr>
<div id="content1"></div>
<div id="content2"></div>
<style>
li{height:20px;}
.bg1{background:red;}
.bg2{background:#00bcd4;}
.bg3{background:white;}
.bg4{background:gray;}
.bg5{background:green;}
.pressed{background-color:#ffc107}
/*li:active{background-color:#ffc107;}*/
</style>
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script>
function attachEvent(obj,cb){
//msMaxTouchPoints ie 判断设备触碰点数
var isTouchDevice="ontouchstart" in window || navigator.msMaxTouchPoints || navigator.MaxTouchPoints;
if(isTouchDevice){
$(obj).bind('touchstart',function(e){
$(this).data('touchon',true)
$(this).addClass('pressed')
});
$(obj).bind('touchmove',function(e){
$(this).data('touchon',false)
$(this).removeClass('pressed')
});
$(obj).bind('touchend',function(e){
if($(this).data('touchon')){
cb.bind(this)();
}
$(this).data('touchon',true)
$(this).removeClass('pressed')
});
}else{
$(obj).bind('mousedown',function(){
$(this).data('touchon',true)
$(this).addClass('pressed')
})
$(obj).bind('mouseup',function(e){
$(this).data('touchon',false)
$(this).removeClass('pressed')
cb.bind(this)();
});
}
}
$.fn.bindtouch = function(cb) {
attachEvent($(this), cb);
};
$('li').click(function(){
$('#content2').text('click时间戳:'+Date.now())
});
$('li').bindtouch(function(){
$('#content1').text('touch时间戳:'+Date.now())
});
</script>