根据页面动态添加类

时间:2017-05-16 20:12:51

标签: javascript html css

我有一个用bootstrap css编写的导航列表:

<ul class="nav navbar-nav navbar-right">
    <li class=""><a href="index.html">Home</a></li>
    <li class=""><a href="about.html">About</a></li>
                </ul>

我的问题是如何使用javascript使用javascript将“active”类添加到“li”标签中?我希望它在index.html for home上具有活动类,对于about.html

也是如此

这可能吗?

2 个答案:

答案 0 :(得分:1)

的JavaScript

var siteList = document.URL.split("/");
var site = siteList[siteList.length - 1];
var list = document.getElementsByTagName("li");
for (var index = 0; index < list.length; index++) {
    var item = list[index];
    var link = item.firstElementChild;
    var href = link ? String(link.href) : "-";
    if (href.replace(".html","") === site) {
        item.classList.add("open");
    } else {
        item.classList.remove("open");
    }
}

说明

您可以使用URL获取当前document.URL,您可能只需要最后一部分,因此您必须将其拆分并获取最后一部分,在您的情况下,是indexabout等。

然后获取所有li元素并迭代它们。 如果他们没有a孩子,则忽略它。 如果他们确实获得href属性并在结尾处删除.html。 如果该文本与site variable相同,则表示您应该打开该元素,否则将其关闭。

答案 1 :(得分:0)

它不干净,可能有更好的方法,但是:

HTML

<ul class="nav navbar-nav navbar-right">
    <li id="navIndex" class=""><a href="index.html">Home</a></li>
    <li id="navAbout" class=""><a href="about.html">About</a></li>
</ul>

JS(某处)

// Map ids with html page names
var pages = { 
    navIndex: "index.html",
    navAbout: "about.html"
};

// Iterate over map
for(var property in pages) {

    // Check to make sure that the property we're iterating on is one we defined
    if(pages.hasOwnProperty(property)) {

        // indexOf will be 0+ if it appears in the string
        if(window.location.href.indexOf(pages[i]) > -1) {

            // we can use property because we defined the map to be same as ids
            // From https://stackoverflow.com/questions/2739667/add-another-class-to-a-div-with-javascript
            var el = document.getElementById(property);
            el.className += el.className ? ' active' : 'active';
            break; // no need to keep iterating, we're done!
        }
    } 
}

这或多或少是&#34;脏&#34;方法,因为它需要的不仅仅是JavaScript才能开始工作(see Nick's answer以实现更清洁的实现)。

首先,我们在<li>元素上设置标识符,然后使用各自的href属性绘制这些标识符。

一旦我们将<li>映射出来,我们就会迭代地图的键(我们将其设置为id s上的<li>属性)检查网站href中是否存在window.location.href属性,如果是:添加active课程并停止搜索,否则我们继续进行卡车运输。