根据滚动期间当前可见的内容突出显示索引中的项目

时间:2018-04-21 17:38:21

标签: javascript html css hugo

在我的html页面中,我有一个CSS属性position: fixed;的目录,并希望在向下滚动页面时突出显示(粗体或斜体)当前读取/显示位置。

                             | yada yada yada ...
1. Section 1                 |
 1.1 Subsection 1            | 1.2 Subsection 2
 1.2 Subsection 2 <-- bold   |   
2. Section 2                 | Lorem ipsum dolor sit amet,
[...]                        | consectetur adipisici elit
                             | [...]

我想保持简单,CSS - 如果可能的话 - 将优先于JS。该网站由Hugo生成,但答案不一定需要特定于Hugo。

非常感谢!

P.s。如果是Hugo特定答案:使用{{ partial "table-of-contents" . }}生成toc

table-of-contents.html

<!-- ignore empty links with + -->
{{ $headers := findRE "<h[1-6].*?>(.|\n])+?</h[1-6]>" .Content }}
<!-- at least one header to link to -->
{{ $has_headers := ge (len $headers) 1 }}
<!-- a post can explicitly disable Table of Contents with toc: false -->
{{ $show_toc := (eq $.Params.toc true) }}
{{ if and $has_headers $show_toc }}
<div class="table-of-contents toc bd-callout">
    <!-- TOC header -->
    <h4 class="text-muted">Table of Contents</h4>
    {{ range $headers }}
        {{ $header := . }}
        {{ range first 1 (findRE "<h[1-6]" $header 1) }}
            {{ range findRE "[1-6]" . 1 }}
                {{ $next_heading := (int .) }}
                <!-- generate li array of the proper depth -->
                {{ range seq $next_heading }}
                    <ul class="toc-h{{ . }}">
                {{end}}
                {{ $base := ($.Page.File.LogicalName) }}
                {{ $anchorId := ($header | plainify | htmlEscape | urlize) }}
                {{ $href := delimit (slice $base $anchorId) "#" | string }}
                <a href="{{ relref $.Page $href }}">
                    <li>{{ $header | plainify | htmlEscape }}</li>
                </a>
                <!-- close list -->
                {{ range seq $next_heading }}
                    </ul>
                {{end}}
            {{end}}
        {{end}}
    {{ end }}
</div>
{{ end }}

1 个答案:

答案 0 :(得分:1)

scroll中,如果您的内容标头和索引项在命名约定中具有iddata属性,则可以跟踪内容标头的可见性。

然后,可见的那个你可以使用命名约定在索引中找到它并在其上添加一个高亮类。

以下是一个工作示例:https://jsfiddle.net/az6z8rze/24/

这里真正的技巧是isElementInViewport功能。您可以像这样使用它,并且可以轻松地将简化示例调整为嵌套索引。

&#13;
&#13;
function isElementInViewport (el) {
    
    //special bonus for those using jQuery
    if (typeof $ === "function" && el instanceof $) {
        el = el[0];
    }
		
    var rect     = el.getBoundingClientRect(),
        vWidth   = window.innerWidth || doc.documentElement.clientWidth,
        vHeight  = window.innerHeight || doc.documentElement.clientHeight,
        efp      = function (x, y) { return document.elementFromPoint(x, y) };     

    // Return false if it's not in the viewport
    if (rect.right < 0 || rect.bottom < 0 
            || rect.left > vWidth || rect.top > vHeight)
        return false;

    // Return true if any of its four corners are visible
    return (
          el.contains(efp(rect.left,  rect.top))
      ||  el.contains(efp(rect.right, rect.top))
      ||  el.contains(efp(rect.right, rect.bottom))
      ||  el.contains(efp(rect.left,  rect.bottom))
    );
}


var handler = function(){
  var visible = 0;
  [1,2,3,4].forEach(function(id){
    if(isElementInViewport($('#'+id))) visible = id;
  })
  
  if(visible){
  	$('#index div').removeClass('active');
    $('#index-'+visible).addClass('active');
  }
};



//jQuery
$(window).on('DOMContentLoaded load resize scroll', handler);
&#13;
#index{
  width: 100%;
  position: fixed;
  top:0;
  left:0;
  background: white;
}

.active{
  font-weight: bold;
  color: green;
}

#content{
  padding-top: 90px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="index">
  <div id="index-1">Section One</div>
  <div id="index-2">Section Two</div>
  <div id="index-3">Section Three</div>
  <div id="index-4">Section Four</div>
</div>

<div id="content">
  <div id="1">
    <h1>Section 1</h1>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum quisquam inventore, magnam maxime explicabo maiores reiciendis, repellendus soluta necessitatibus, vero recusandae! Delectus minima, dolore necessitatibus autem. Eveniet harum, asperiores obcaecati.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit blanditiis suscipit delectus aut neque libero ducimus corporis, cum ipsum a, vitae sed aperiam doloribus quos accusamus harum rem hic totam?
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, inventore eligendi sed quam omnis ipsam nesciunt quis debitis dignissimos natus molestias rem eos! Fugiat voluptates a nam laudantium porro quisquam!
  </div>
  
    <div id="2">
    <h1>Section Two</h1>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum quisquam inventore, magnam maxime explicabo maiores reiciendis, repellendus soluta necessitatibus, vero recusandae! Delectus minima, dolore necessitatibus autem. Eveniet harum, asperiores obcaecati.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit blanditiis suscipit delectus aut neque libero ducimus corporis, cum ipsum a, vitae sed aperiam doloribus quos accusamus harum rem hic totam?
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, inventore eligendi sed quam omnis ipsam nesciunt quis debitis dignissimos natus molestias rem eos! Fugiat voluptates a nam laudantium porro quisquam!
  </div>
  
    <div id="3">
    <h1>Section Three</h1>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum quisquam inventore, magnam maxime explicabo maiores reiciendis, repellendus soluta necessitatibus, vero recusandae! Delectus minima, dolore necessitatibus autem. Eveniet harum, asperiores obcaecati.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit blanditiis suscipit delectus aut neque libero ducimus corporis, cum ipsum a, vitae sed aperiam doloribus quos accusamus harum rem hic totam?
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, inventore eligendi sed quam omnis ipsam nesciunt quis debitis dignissimos natus molestias rem eos! Fugiat voluptates a nam laudantium porro quisquam!
  </div>
  
    <div id="4">
    <h1>Section Four</h1>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum quisquam inventore, magnam maxime explicabo maiores reiciendis, repellendus soluta necessitatibus, vero recusandae! Delectus minima, dolore necessitatibus autem. Eveniet harum, asperiores obcaecati.
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit blanditiis suscipit delectus aut neque libero ducimus corporis, cum ipsum a, vitae sed aperiam doloribus quos accusamus harum rem hic totam?
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, inventore eligendi sed quam omnis ipsam nesciunt quis debitis dignissimos natus molestias rem eos! Fugiat voluptates a nam laudantium porro quisquam!
  </div>
</div>
&#13;
&#13;
&#13;

致谢:isElementInViewport回答this answer