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

Javascript JS/jQuery-将侧导航条的滚动条设置到特定位置,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个侧面导航条,看起来像这样: 。滚动框{ 溢出:隐藏; 宽度:128px; } .填料{ 高度:256px; 溢出y:自动; } .选择器{ 背景色:#369; 填充:8px 4px; 文本对齐:居中; 柔性生长:1; 显示:内联块; 光标:指针; 框大小:边框框; 转换:.1s!重要; } .酒吧{ 高度:8px; 宽度:100%; 背景色:#808080; } .标签{ 填充:4px8px; 背景色:#707070; } .主动{ 背景颜色:浅灰色; 颜色:#369; } 日期 2

我有一个侧面导航条,看起来像这样:

。滚动框{
溢出:隐藏;
宽度:128px;
}
.填料{
高度:256px;
溢出y:自动;
}
.选择器{
背景色:#369;
填充:8px 4px;
文本对齐:居中;
柔性生长:1;
显示:内联块;
光标:指针;
框大小:边框框;
转换:.1s!重要;
}
.酒吧{
高度:8px;
宽度:100%;
背景色:#808080;
}
.标签{
填充:4px8px;
背景色:#707070;
}
.主动{
背景颜色:浅灰色;
颜色:#369;
}

日期
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月15日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日
2016年8月4日

我认为您可以使用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的顶部。滚动到顶部

演示可以在

上找到,也许这可以。(我现在不能测试…)

基本上,我们得到div中没有id“today”的每个元素,并添加这些元素的高度。当我们最终到达“今天”时,我们将滚动条设置为过去添加到一起的每个元素的高度,并退出循环

$(document).ready(function(){
    var height = 0;
    $(".filler *").each(function () {
        if($(this).is("#today"))
        {
            return false; //to get out of the .each
        }
        else
        {
            height += $(this).height();
        }
    })
    $( "div.demo" ).scrollTop(height); //set the scrollbar
});

非常感谢。不完全确定这是如何工作的,但它确实如此@4lackof,我刚刚添加了更多的注释,因此您可以了解jQuery代码的基本工作原理