2013-05-16 107 views
0

所以我有一些JavaScript,當一個人點擊並拖動或拖動他們的手指(在移動設備上),並通過一系列圖像循環來創建360圖像旋轉效果。繼承人的代碼。在javascript中模擬鼠標拖動/觸摸拖動運動

$(document).ready(function ($) { 
    var $product = $('#product'), 
     $imgs = $product.find(".child"), 
     imageTotal = $imgs.length - 1, 
     clicked = false, 
     widthStep = 20, 
     currPos, 
     currImg = 0, 
     lastImg = 0; 
    $imgs.bind('mousedown', function (e) { 
     e.preventDefault(); // prevent dragging images 
    }) 
     .filter(':gt(0)').addClass('notseen'); 

    $product.bind('mousedown touchstart', function (e) { 
     if (e.type == "touchstart") { 
      currPos = window.event.touches[0].pageX; 
     } else { 
      currPos = e.pageX; 
     } 
     clicked = true; 

    }); 
    $(document) 
     .bind('mouseup touchend', function() { 
     clicked = false; 
    }) 
     .bind('mousemove touchmove', function (e) { 
     if (clicked) { 
      var pageX; 
      if (e.type == "touchmove") { 
       pageX = window.event.targetTouches[0].pageX; 
      } else { 
       pageX = e.pageX; 
      } 
      widthStep = 20; 
      if (Math.abs(currPos - pageX) >= widthStep) { 
       if (currPos - pageX >= widthStep) { 
        currImg++; 
        if (currImg > imageTotal) { 
        currImg = 0;} 
       } else { 
        currImg--; 
        if (currImg < 1) { 
         currImg = imageTotal; 
        } 
       } 
       currPos = pageX; 
       $imgs.eq(lastImg).addClass('notseen'); 
       $imgs.eq(currImg).removeClass('notseen'); 
       lastImg = currImg; 
       // $obj.html('<img src="' + aImages[options.currImg] + '" />'); 
      } 
     } 
    }); 
}); 

現在用這個作爲基礎,我想模擬鼠標或者手指被draged有一定的距離,一旦文件被加載,我想模擬這個函數創建一個自動旋轉。

現在我知道我需要在這裏使用mousedown/touchstartmousemove/touchmove函數,但從那裏我有點失落如何啓動它並設置模擬距離。任何想法和幫助表示讚賞。

回答

1

一個簡單的方法是重構代碼,將touchstart和touchmove作爲自己的函數/對象進行公開。

這將允許你從任何地方在任何情況下打電話給他們,而不必依賴實際的事件觸發。

我最近看了一個真棒文章這也解釋瞭如何有效地做到這一點的一些建議:https://shanetomlinson.com/2013/testing-javascript-frontend-part-1-anti-patterns-and-fixes/

+0

那是一個偉大的文章,但我不知道如何這個概念工作到我的文檔。我想我真正想做的是兩件事之一。既可以使用jquery模擬鼠標移動,也可以將自動播放功能添加到腳本中。有任何想法嗎? – mhartington