gpt4 book ai didi

javascript - JS/jQuery - 将侧导航栏的滚动条设置到特定位置

转载 作者:行者123 更新时间:2023-11-27 23:25:05 24 4
gpt4 key购买 nike

我有一个侧边导航栏,看起来像这样:

.scroll-box {
overflow: hidden;
width: 128px;
}
.filler {
height: 256px;
overflow-y: auto;
}
.selector {
background-color: #369;
padding: 8px 4px;
text-align: center;
flex-grow: 1;
display: inline-block;
cursor: pointer;
box-sizing: border-box;
transition: .1s !important;
}
.bar {
height: 8px;
width: 100%;
background-color: #808080;
}
.label {
padding: 4px 8px;
background-color: #707070;
}
.active {
background-color: lightgrey;
color: #369;
}
<div class="scroll-box">
<div class="label">Dates</div>
<div class="filler">
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector active" id="today">15-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
</div>
<div class="bar"></div>
</div>

我想得到它,以便在加载页面时,它会自动将侧边导航栏的 View 置于 today id 元素的中心。我试过放置 myUrl#today 但这改变了整个页面滚动,这是我不想要的。我

我只希望侧导航栏中的滚动条更改其位置并以 #today 位为中心。有谁知道这样做的方法吗?

我也愿意使用 jQuery 和 JS。

谢谢。

最佳答案

我认为你可以使用 jQuery 代码,例如

$(document).ready(function(){
// when document is ready
// first check if #today is defined in HTML
// the $('') is the jQuery selector of to select an element
// $('#today') means select an element with the ID "today"
// the .length attribute is default javascript attribute to check
// how many of elements selected has existed
if($('#today').length > 0){
// the offset() function is a jQuery function that is used for check the
// relative distance from the border of current element to its parent
var distance_to_top = $('#today').offset().top;
var top_label_height = $('.label').height();
var distance_to_scroll = distance_to_top - top_label_height - 8;
// 8 px is body margin on jsfiddle
// scrollTop() function is another jQuery function to scroll an
// overflow element
$('.filler').scrollTop(distance_to_scroll);
}
});

找到今天元素相对于其父元素的偏移量,然后减去标签高度,因为标签将覆盖#today 的顶部。滚动到顶部

可以在here 找到演示。

关于javascript - JS/jQuery - 将侧导航栏的滚动条设置到特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38966280/

24 4 0