0

我使用 HTML、CSS 和 JavaScript 创建了一个自定义内容滚动框。当您尝试拖动滚动条时,它会跳到滚动条的左边缘。知道为什么我错过了什么吗?

var scrollbar = document.getElementById("scrollbar");
var barWidth = 300;
var scrollbarWidth = 40;

scrollbar.addEventListener("mousedown", function(e) {
    window.addEventListener("mousemove", hScroll, null);
}, null)

window.addEventListener("mouseup", function(e) {
    window.removeEventListener("mousemove", hScroll, null);
}, null);

function hScroll(e) {
    var scroller_pos = e.clientX - offset;
    if (scroller_pos <= 0) scroller_pos = 0;
    else if (scroller_pos >= barWidth-scrollbarWidth) scroller_pos = barWidth-scrollbarWidth;
    scrollbar.style.marginLeft = scroller_pos + "px";
}
4

1 回答 1

1

在 mousedown 上,您应该计算正方形与bar左边缘的距离与鼠标 x 位置与同一边缘的距离之间的偏移量。然后在移动时,您应该将其添加到正方形的新位置。

 _____
|     |
|   .<+--click
|___|_|
|<->|
  |
offset
于 2012-08-20T14:47:33.893 回答