touch的深入理解

2020-10-30 10:35:11 浏览数 (1)

代码语言:javascript复制
<!doctype html> 
<html> 
<head> 
	<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta charset="utf-8"> 
    <title></title>
    <style type="text/css">
*{margin: 0;padding: 0;list-style: none;}
#div1{width: 200px;height: 200px;background: black;}


    </style> 
</head>
<body>
<div id='div1'></div>
<script type="text/javascript">
	/*
	div1.onclick = function(){
		alert(1);
	};
	*/
	/*
	div1.touchstart = function(){
		alert(1);
	}
	*/
var div1=document.querySelector("#div1");
	div1.addEventListener('touchstart',function(){
		alert(1);
	},false);

</script>
</body>
</html>

记住,touch只在这里有效.

效果:

代码语言:javascript复制
<!doctype html> 
<html> 
<head> 
	<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta charset="utf-8"> 
    <title></title>
    <style type="text/css">
*{margin: 0;padding: 0;list-style: none;}
#div1{width: 200px;height: 200px;background: black;}


    </style> 
</head>
<body>
<div id='div1'></div>
<script type="text/javascript">
	/*
	div1.onclick = function(){
		alert(1);
	};
	*/
	/*
	div1.touchstart = function(){
		alert(1);
	}
	*/

	div1.addEventListener('touchmove',function(){
		//alert(1);
		this.style.background = 'rgb(' parseInt(Math.random()*256) ',' parseInt(Math.random()*256) ',' parseInt(Math.random()*256) ')'
	},false);

</script>
</body>
</html>

256是因为只有范围最大只在256这个范围内.

代码语言:javascript复制
<!doctype html> 
<html> 
<head> 
	<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta charset="utf-8"> 
    <title></title>
    <style type="text/css">
*{margin: 0;padding: 0;list-style: none;}
#div1{width: 200px;height: 200px;background: black;}


    </style> 
</head>
<body>
<div id='div1'></div>
<script type="text/javascript">
	/*
	div1.onclick = function(){
		alert(1);
	};
	*/
	/*
	div1.touchstart = function(){
		alert(1);
	}
	*/

	div1.addEventListener('touchend',function(){
		//alert(1);
		alert(1);
	},false);

</script>
</body>
</html>

注意一下,是结束哈

代码语言:javascript复制
<!doctype html> 
<html> 
<head> 
	<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta charset="utf-8"> 
    <title></title>
    <style type="text/css">
*{margin: 0;padding: 0;list-style: none;}
#div1{width: 200px;height: 200px;background: black;
	position: relative;
}
#div2{
	position: absolute;
	width: 50px;height: 50px;
	background: red;left: 500px;top: 500px;
}

    </style> 
</head>
<body>
<div id='div1'>
	<div id='div2'></div>
</div>
<script type="text/javascript">
	


div1.onclick = function(ev){
	console.log(ev)
	alert(1);
};
div2.onclick = function(ev){
	ev.cancelBubble=true;
};



</script>
</body>
</html>

注意下;这里代表了ev.cancelBubble=true;移动端的阻止事件冒泡的代码.

0 人点赞