[英]stop a previous function from continuing to be excuted with jquery
我有以下 function 來創建 slider。 它工作(幾乎完美)......我現在遇到的問題是,一旦你點擊 slider 它會像它應該的那樣移動,但是當我釋放鼠標時我不知道如何阻止它移動?
建議? 謝謝!
var moveSlider = function(){
//sets the current position and offset variables
var currentPosition;
var offset;
//looks for the mousedown event on the slider
$("#slider").mousedown(function(e){
//sets the offset = to the mouse coordinate of the page - the offset of the slider
offset = e.pageX - this.offsetLeft;
console.log("offset: " + offset);
//tracks the mosemovement in the document
$(document).mousemove(function(e){
currentPosition = e.pageX - offset;
//takes the mouse current position (minues the offset) and sets an absolute position
$('#slider').css('left', currentPosition + "px");
console.log("CURRENT POSITION: " + currentPosition);
//checks to make sure it's within the box
if(currentPosition <= 0){
$('#slider').css('left', 0 + "px");
}else if(currentPosition >= 400){
$('#slider').css('left', 400-20 + "px");
}
});
});
$("#slider").mouseup(function(){
$('#slider').css('left', currentPosition + "px")
console.log("Fixed");
});
};
編輯:MVCHR,我離開了你的例子,並想出了以下內容。 鼠標移動仍然有效,但是當您釋放鼠標時,它會繼續移動。 我確定我錯過了一些愚蠢的東西
再次編輯:愚蠢的錯誤,我仍然讓鼠標移到那里。 把它拿出來,現在可以正常工作了:謝謝 :)
再次感謝
var moveSlider = function(){
//sets the current position and offset variables
var currentPosition;
var offset;
var rightOffset
//looks for the mousedown event on the slider
$("#slider").mousedown(function(e){
//sets the offset = to the mouse coordinate of the page - the offset of the slider
offset = e.pageX - this.offsetLeft;
console.log("offset: " + offset);
$(document).bind('mousemove', mmHandler);
});
var mmHandler = function (e) {
//tracks the mosemovement in the document
$(document).mousemove(function(e){
currentPosition = e.pageX - offset;
//takes the mouse current position (minues the offset) and sets an absolute position
$('#slider').css('left', currentPosition + "px");
console.log("CURRENT POSITION: " + currentPosition);
//checks to make sure it's within the box
if(currentPosition <= 0){
$('#slider').css('left', 0 + "px");
}else if(currentPosition >= 400){
$('#slider').css('left', 400-20 + "px");
}
});
};
$(document).mouseup(function(e) {
// some code then
$(document).unbind('mousemove', mmHandler);
});
};
在您的鼠標向上事件處理程序中添加:
$(document).unbind('mousemove');
您可能應該將用於處理綁定鼠標移動的 function 放入您可以傳遞給 unbind 的內容中,因為上面的代碼將影響文檔上可能設置的所有 mousemove 處理程序。
如果您有其他不想刪除的綁定到mousemove
的函數,請將mousemove
function 移動到您在mousedown
上bind
並在mouseup
上unbind
的命名 function 。 請注意,假設您的 slider 不會垂直移動,您還需要將mouseup
放在document
而不是#slider
上。
像這樣的東西:
var mmHandler = function (e) {
// mousemove code here
};
$("#slider").mousedown(function(e) {
// some code then
$(document).bind('mousemove', mmHandler);
});
$(document).mouseup(function(e) {
// some code then
$(document).unbind('mousemove', mmHandler);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.