我具有以下创建滑块的功能。它的工作原理(几乎完美)...我现在遇到的问题是,一旦单击滑块,它就会像应该的那样移动,但是当我释放鼠标时我无法弄清楚如何阻止它移动?
有什么建议吗?
谢谢!
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');
您可能应该将用于处理绑定的鼠标移动的函数放到可以传递给取消绑定的对象中,因为上面的代码将影响可能设置的文档上的所有mousemove处理函数。
unbind api docs