觸摸屏的div拖動Demo

       話說我剛剛從PC的Web開發轉到移動的Web開發……

       當前移動Web開發不得不面對強大的流行的Android,IOS這兩大觸摸屏系統啊,畢竟這是熱門啊,用戶都在這裏。

       這次因爲開發需要,我得試着做一個背景可以拖動的div頁面。當一切都在PC上做完之後,轉到手機進行測試,竟然無效啊,拖動無效。經過調試發現mousemove事件(還有mousedown,mouseup)的clientX的屬性在PC端幾款瀏覽器都沒問題,在平板的Android瀏覽器和QQ瀏覽器下都是未定義undefined。

       當時想是不是因爲event.clientX在移動端不支持,然後就試了一下offsetXscreenX,結果都一樣,這個時候都快崩潰了我。 

       按說mousedown,mouseup,mousemove和touchstart,touchend,touchmove之間是可以互通的,也就是說一般面向pc開發的mouse時間對touch事件有效,據說是效率有差異。但是pc上測試沒有任何問題,在手機上就是無效。
       然後百度了很久很久……

       終於在一個討論touch相關事件的例子中看到別人已經經過測試的e.touches[0].pageX,光這個屬性還是不夠的,發現使用jquery爲div綁定touch事件後這個屬性也是未定義,必須使用原生的

document.getElementById("moveid").addEventListener('touchmove',movemouse);
       就這樣,問題就解決了。

       最後,貼上demo的代碼,希望給遇到同樣問題的你提供幫助。

<html> 
<head> 
	<meta charset="UTF-8">
    <style type="text/Css">
		body{background-color:#000000;}
		.window{position:absolute;z-index:1;overflow:hidden;width:600px;height:400px;background-color:red;left: 0px;}
		.dragme{position:relative;background-image:url('img/testbg.png');width:800px;height:400px;} 
	</style> 

<script type="text/javascript" charset="utf-8" src="js/jquery.min.js"></script>
<script type="text/javascript"> 
var isdrag=false; 
var tx,x;  
$(function(){
	document.getElementById("moveid").addEventListener('touchend',function(){
		sdrag = false;
	});
	document.getElementById("moveid").addEventListener('touchstart',selectmouse);
	document.getElementById("moveid").addEventListener('touchmove',movemouse);
});
function movemouse(e){ 
  if (isdrag){ 
   var n = tx + e.touches[0].pageX - x;
   $("#moveid").css("left",n);
   return false; 
   } 
} 

function selectmouse(e){ 
   isdrag = true; 
   tx = parseInt(document.getElementById("moveid").style.left+0); 
   x = e.touches[0].pageX;  
   return false; 
} 
</script> 

</head> 
<body> 
<div align="left" class="window">
	 <div id="moveid"  class="dragme">
	 	<h1>這是一個可以通過觸摸屏拖動的demo</h1>
	 	<p>
	 		這個demo花費了我半天時間,原因是以前從來沒有做過面向觸摸屏的Web,按說mousedown,mouseup,mousemove和touchstart,touchend,touchmove
	 		之間是可以互通的,也就是說一般面向pc開發的mouse時間對touch事件有效,據說是效率有差異。但是pc上測試沒有任何問題,在手機上就是無效。
	 		然後……
	 		然後百度了很久很久……
	 	</p>
	 </div>
 </div>
</html>



 

 

發佈了34 篇原創文章 · 獲贊 23 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章