我有一张图片,我已将 ID #scroller 指定给它。我想做的是根据鼠标的 x 坐标水平移动滚动条,但仅限于按住鼠标时。我正在尝试将滚动条移动到名为 #bar 的水平线上。滚动条可以移动的量取决于条的宽度。到目前为止,这是我的代码。
$(document).ready(function() {
var barWidth = $("#bar").width();
var mouseDown = false;
$(document).mousedown(function() {
mouseDown = true;
});
$(document).mouseup(function() {
mouseDown = false;
});
$(document).on("mousemove", function(e) {
if (mouseDown) {
if (e.pageX >= barWidth) {
$("#debug").html(JSON.stringify(e.pageX, undefined, 4));
$("#scroller").css("left", barWidth);
} else {
$("#debug").html(JSON.stringify(e.pageX, undefined, 4));
$("#scroller").css("left", e.pageX);
}
}
});
});
#debug 只是在屏幕上打印一些东西。它有助于调试。它没有按预期工作。我希望滚动条在按住鼠标并移动时移动。
最佳答案
您的问题很可能是因为您没有更改滚动条的位置属性。它应该是 style="position:absolute"
或 style="position:relative"
否则 .css("left", barWidth)
不会生效。在这里查看 js fiddle :
https://jsfiddle.net/0m0j35oc/
此外,最好在事件本身上跟踪按钮(有关更多详细信息,请参见 question),因为 mouseup/mousedown 事件可能会在页面外部触发,从而有效地使缓存状态不同步。请参阅此处的示例:
关于javascript - jquery - 按住鼠标时的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34520490/