将元素保持在可滚动分区的中心



我正在为某种日历绘制时间表,在日常视图中,有一个垂直滚动和一条指示当前时间的红线。请以这个jsbin为例https://jsbin.com/pazufivige/edit?html,输出

<div style="width: 500px; overflow: scroll">
<div style="width: 5000px; height: 100px; background-color:grey;position: relative;">
<div style="position: absolute; height: 100%; width: 2px; background-color: #EF5350; z-index: 5; left: 8%";></div>
</div>
</div>

我想把红线保持在div的中心,所以我想让可滚动的div滚动到正确的位置,这样它就保持在在中间。红线每分钟更新一次,并且在计划的顶部,所以我必须每分钟计算滚动位置。我该怎么做?我在谷歌上搜索了很多,但真的找不到与我的问题类似的东西,有人能把我推向正确的方向吗?

您必须找到"红线"的位置并滚动窗口,使窗口左侧的红线位置为窗口宽度的一半。

要遵循的简单步骤:1.从窗口左侧找到直线的相对位置。2.找到窗口的宽度。3.使用scrollLeft方法滚动,使红线左侧的宽度与红线右侧的宽度相同。

$(document).ready(function(){
width = $("#myWindow").width();
linePosition = $("#redLine").position().left;
console.log(linePosition);
let scroll= linePosition - (width/2);
console.log(scroll)
$("#myWindow").scrollLeft(scroll);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myWindow" style="width: 500px; overflow-x: scroll">
<div style="width: 5000px; height: 100px; background-color:grey;position: relative;">
<div id="redLine" style="position: absolute; height: 100%; width: 2px; background-color: #EF5350; z-index: 5; left: 45%";></div>
</div>
</div>

最新更新