我有一个侧面导航栏,如下所示:
.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 元素相对于其父元素的偏移量,然后减去标签高度,因为标签将覆盖在 #today 的顶部。滚动到顶部
演示可以在 here 找到
关于javascript - JS/jQuery - 将侧导航栏的滚动条设置到特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38966280/