【发布时间】:2011-04-28 20:43:43
【问题描述】:
我有以下函数来创建一个滑块。它工作(几乎完美)......我现在遇到的问题是,一旦你点击滑块,它就会像它应该的那样移动,但是当我释放鼠标时我不知道如何阻止它移动?
建议? 谢谢!
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);
});
};
【问题讨论】:
标签: javascript jquery slider jquery-animate