2011-05-05 45 views
0

我在mousemove事件定位一個div通過設置它的CSS左側位置,其中的演示可以發現在:jQuery的幻燈片停止在左邊的位置

http://jsfiddle.net/JLtT3/53/

我有什麼麻煩與設置左邊界和右邊界停止。

無論我做什麼,它似乎都超過了我設置的邊界(左側和右側),所以-13px左側。

如果我登錄到螢火蟲它進入減去的數字,儘管事實上我的左側位置:

如果(SBAR < 0)

在我的代碼

jQuery的(例如工作包括在上述網址HTML):

$(document).ready(function() { 
    var statusbar = $(".jspDrag"); 

    statusbar.mousedown(function(event) { 
     handleMouseDown(event, this); 
    }); 

    $("body").mouseup(function(event) { 
     handleMouseUp(event, this); 
    }); 
}); 

function handleMouseDown(e, sbar) { 
    var sbarPosition = $(sbar).position(); 
    var sbarPosition = e.pageX - sbarPosition.left; 
    var endRightPosition = $('.jspCapRight').position(); 
    var endRightPosition = endRightPosition.left - $(sbar).width(); 
    var endLeftPosition = $('.jspCapLeft').position(); 
    var endLeftPosition = endLeftPosition.left; 

    if (e.button == 0) 
    { 
     $("body").bind('mousemove', function(event) { 
      handleMouseMove(event, $(sbar), sbarPosition, endLeftPosition, endRightPosition); 
     }); 
    } 
} 

function handleMouseUp(e, sbar) { 
    $("body").unbind('mousemove'); 
} 

function handleMouseMove(e, sbar, sbarMousePosition, endLeftPosition, endRightPosition) { 
    var moveXposition = e.pageX - sbarMousePosition; 
    var sbarLeft = $(sbar).position(); 
    var sbarLeft = sbarLeft.left; 
    console.log(sbarLeft); //firebug 

    if ((sbarLeft >= endLeftPosition) && (moveXposition < endRightPosition)) 
    { 
     $(sbar).css('left', moveXposition); 
    } 
} 

回答

1

應該這樣:

if ((sbarLeft >= endLeftPosition) && (moveXposition < endRightPosition)) 

真的是這樣的:

if ((moveXposition>= endLeftPosition) && (moveXposition < endRightPosition)) { 

您似乎在檢查當前位置(sbarLeft)未超過左邊界而不是新位置(moveXposition)。

+0

是謝謝你,這就是問題所在。 – StuR 2011-05-05 20:49:09

2

爲什麼要重新發明輪子? jQuery UI有一個合適的可拖動實現,沒有你需要處理的令人討厭的錯誤,比如當鼠標離開窗口時卡住拖動,意外的文本選擇阻止下一次拖動等等。你甚至可以構建一個定製的jQuery UI文件在網站上,如果你不需要整個事情來縮短代碼庫。看看這個小提琴:http://jsfiddle.net/JLtT3/54/

實現與jQuery UI:

$(document).ready(function() { 
    $(".jspDrag").draggable({ 
     containment: '.jspHorizontalBar', 
     axis: 'x', 
     drag: function(event,ui){ 
      //do your stuff, ui.position.left is the current position 
     } 
    }); 
}); 
+0

如果可能的話,我希望不使用UI,因爲我希望這個應用程序儘可能輕量級,這是唯一可以從我使用ui中受益的代碼,說過爲了我可能會遇到的錯誤爲了克服,我會明智地使用它。 – StuR 2011-05-06 08:42:00

+1

如果你去http://jqueryui.com/download你可以自定義你的包,如果你只想拖動,選擇沒有主題的Core,Widget,Mouse,Draggable,它只產生28.4k的小.js文件。 – DarthJDG 2011-05-06 08:47:31