2013-02-25 78 views
-1

我有一個普通的javascript,用於拖動和移動HTML頁面中的DIV標記 這可以很好地處理鼠標移動,鼠標移動和鼠標移動事件 現在我想擴展它並使其適用於觸摸設備iPhone手機) 有人可以幫助我做到這一點如何用普通的javascript實現iOS的觸摸事件?

if (document.getElementById) { 

     (function() { 

      var n = 500; 
      var dragok = false; 
      var y, x, d, dy, dx; 

      function move(e) { 
       if (!e) e = window.event; 
       if (dragok) { 
        d.style.left = dx + e.clientX - x + "px"; 
        d.style.top = dy + e.clientY - y + "px"; 
        return false; 
       } 
      } 

      function down(e) { 
       if (!e) e = window.event; 
       var temp = (typeof e.target != "undefined") ? e.target : e.srcElement; 
       if (temp.tagName != "HTML" | "BODY" && temp.className != "dragclass") { 
        temp = (typeof temp.parentNode != "undefined") ? temp.parentNode : temp.parentElement; 
       } 
       if (temp.className == "dragclass") { 
        dragok = true; 
        temp.style.zIndex = n++; 
        d = temp; 
        dx = parseInt(temp.style.left + 0); 
        dy = parseInt(temp.style.top + 0); 
        x = e.clientX; 
        y = e.clientY; 
        document.onmousemove = move; 
        return false; 
       } 
      } 

      function up() { 
       dragok = false; 
       document.onmousemove = null; 
      } 

      document.onmousedown = down; 
      document.onmouseup = up; 

      document.body.addEventListener("touchstart", down, true); 
      document.body.addEventListener("touchcancel", up, true); 
      document.body.addEventListener("touchmove", move, true); 


     })(); 

回答

0

你的事件:touchstart,touchmove和touchend。他們的工作方式相同

https://developer.mozilla.org/en-US/docs/DOM/Touch_events

來實現,這將是測試瀏覽器是否能夠觸摸的,通過像Modernizr的圖書館,或者是最好的辦法:

var isTouch = "ontouchstart" in window; 

if(isTouch){ 
    el.addEventListener('touchstart', handlerStart); 
    el.addEventListener('touchmove', handlerMove); 
    el.addEventListener('touchend', handlerEnd); 
} else{ 
    el.addEventListener('mousedown', handlerStart); 
    el.addEventListener('mousemove', handlerMove); 
    el.addEventListener('mouseup', handlerEnd); 
} 

根據在你想做什麼的複雜性上,這兩種情況下的處理程序可能是相同的,但是你可能必須使用不同的處理程序來獲得鼠標和觸摸效果

+0

我認爲這是用於畫布的,在我的情況下我並不使用一個畫布,只是美國ng一個普通的javascript來移動div對象。更新了問題 – SSK 2013-02-25 18:55:01

+0

中的代碼這適用於DOM元素,這是正確的方式 – 2013-02-26 00:13:58