我正在为某种日历制作时间轴,在每日 View 中,有一个垂直滚动条和一条指示当前时间的红线。请以这个jsbin为例https://jsbin.com/pazufivige/edit?html,output
<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>
关于javascript - 使元素在可滚动的 div 中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51705021/