[英]Calculate Scroll Position using vanilla javascript
The wrapper overflows on x direction so it has horizontal scrolling, and the table inside.body overflows on y direction so it has vertical scrolling.包装器在 x 方向上溢出,因此它具有水平滚动,并且 table inside.body 在 y 方向上溢出,因此它具有垂直滚动。 The Markup looks like below.标记如下所示。
<div class="container"> <div class="wrapper"> <div class="head"> <table>...</table> </div> <div class="body"> <table>...</table> </div> </div> </div>
I've removed the default browser scrollbars and created custom scrollbars
.我删除了默认浏览器滚动条并创建了自定义scrollbars
。 The custom scrollbars are created for the container element.为容器元素创建自定义滚动条。 When wrapper scrolls horizontally then container's x-scrollbar
scrolls, and when table inside body scrolls vertically then container's y-scrollbar scrolls.当 wrapper 水平滚动时,容器的x-scrollbar
滚动,当 body 内的 table 垂直滚动时,容器的 y-scrollbar 滚动。
The problem is with the vertical scrollbar.问题出在垂直滚动条上。 When I click and drag and the vertical scrollbar's thumb, I've to update the scrollTop
of the table inside body.当我单击并拖动垂直滚动条的拇指时,我必须更新 body 内表格的scrollTop
。 I'm founding it hard to figure out the right calculations to update the scrollTop
.?我发现很难找出正确的计算来更新scrollTop
。? Someone help me fix this.有人帮我解决这个问题。
I've set up the mousedown
, mousemove
and mouseup
listeners for the y-scrollbar's thumb to calculate the amount of distance dragged, but how do I calculate the scrollTop
of the table inside body with respect to the amount of distance dragged in the y-scrollbar
?我已经为 y-scrollbar 的拇指设置了mousedown
、 mousemove
和mouseup
侦听器来计算拖动的距离量,但是我如何计算 body 内表格的scrollTop
相对于在y-scrollbar
中拖动的距离量y-scrollbar
?
I figured out the correct calculations.我想出了正确的计算。
var elem = document.querySelector('.body table'); // Content to be scrolled.
var yTrack = document.querySelector('.track.y'); // scroll-track-y
var yBar = yTrack.querySelector('.bar'); // scroll-thumb-y
On mousedown
event, I'm setting the intial values to an object.在mousedown
事件中,我将初始值设置为 object。 On mousemove
event, I'm updating the scrollTop
of the element to be scrolled.在mousemove
事件中,我正在更新要滚动的元素的scrollTop
。 Then on mouseup
event i'm setting that object to null.然后在mouseup
事件中,我将 object 设置为 null。
function yBar_OnMouseDown(e)
{
initCoords = {
axis: 'y',
abs: e.pageY,
bar: yBar,
p0: yBar.offsetTop
};
};
function yBar_OnMouseMove(e)
{
if (initCoords && initCoords.axis === 'y')
{
var maxElemScroll = elem.scrollHeight - elem.clientHeight;
var room = yTrack.scrollHeight - yBar.clientHeight;
var diff = e.pageY - initCoords.abs;
var abs = initCoords.p0 + diff;
var maxTrackScroll = yTrack.offsetHeight - yBar.offsetHeight;
abs = abs < 0 ? 0 : maxTrackScroll < abs ? maxTrackScroll : abs;
elem.scrollTop = maxElemScroll * abs / room;
}
};
function yBar_OnMouseUp(e)
{
initCoords = null;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.