最近在网页中添加了一个目录模块,但是这个目录模块有点长,就想方设法的控制这个模块。
为了方便用户浏览,我决定要实现一个功能:在打开目录的时候 让模块把当前网页对应的目录项显示出来。
这里需要分为2步:
第一步,如何在一个普通的目录项中加入特定的信息,以表明这一项是对应当前网页的。
第二步才需要控制模块自动滚动到特定的目录项。
由于我的网站使用了bootstrap,这个目录模块相应的用了'nav nav-pills' class,而我之前有见到如果把对应的目录项<li> 加入一个class 'active' ,那么这个目录项就会有一个蓝色的底色。在显示效果上就有了不同。所以我决定就使用这个class。
那么就需要对网页内容进行判断。一开始我以为无法判断网页的address,就开始截取网页内容,和目录里的进行比较。直到我看到了w3school上对浏览器的一些信息采集。
location.pathname
这个方法可以获取URL的路径。比如当时我的网页的路径是http://localhost:5000/sanguozhi/7,获取的结果是/sanguozhi/7。再通过js的string方法split,用符号/获取最后一个数字字符,这样就能拿到网页的id。而且这个id就是这个网页在目录中的id。
var page_path = location.pathname;
var path_arr = page_path.split("/");
var nav_list = document.getElementById('navigation-bar').getElementsByClassName('nav nav-pills')[0];
target_child = nav_list.childNodes[parseInt(path_arr[2])];
target_child.setAttribute('class', "active");
nav_list获取的是目录的内容,需要注意的是:获取出来之后就已经不是DOM文档了,而是XML,所以下面我们的操作都是js针对XML的操作。
target_child就应该能拿到对应的目录项
但是我们运行之后发现居然没有任何效果。我表示无法理解。
通过打印childNodes.length,我发现居然不是我之前设定的数字,通过进一步观察,我发现了原因。
HTML如下:
<div id="navigation-bar" style="display: none;">
<ul class="nav nav-pills nav-stacked">
<li><a href="1">cc</a></li>
<li><a href="2">cp</a></li>
<li><a href="3">cr</a></li>
<li><a href="4">cf</a></li>
<li><a href="5">hf</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">deyl <span class="caret"></span></a>....</li>
....
</div>
嗯,好像是每个<li>之前的空格影响了对XML的解析。
还是使用jquery吧
target_child = $('#navigation-bar .nav.nav-pills > li')[parseInt(path_arr[2])];
还是不对,怎么总是显示下一个呢?原来js是从0开始计数,而我获取的id是从1开始,所以最后的代码是:
target_child = $('#navigation-bar .nav.nav-pills > li')[parseInt(path_arr[2]) - 1];
下面要添加class。本来想使用addClass,还是不行,看来取出来之后还是XML,还是使用XML的setAttribute方法。
target_child.setAttribute('class', "active");
又不对了,如果本来<li>有一个class,就会被替换。
最后修改为:
target_child.setAttribute('class', target_child.getAttribute('class') + " active");
所以第一步完成,代码总共4行:
var page_path = location.pathname;
var path_arr = page_path.split("/");
target_child = $('#navigation-bar .nav.nav-pills > li')[parseInt(path_arr[2]) - 1];
target_child.setAttribute('class', target_child.getAttribute('class') + " active");