如何获取a:仅在访问过的最后一页上访问过的选择器?

时间:2016-02-14 18:28:34

标签: html css dreamweaver

目前,我最近在网站上查看的所有网页都已更改为我指定的颜色。我想要完成的是只有页面查看的最后一个具有我指定的颜色。

谢谢!

1 个答案:

答案 0 :(得分:1)

我很无聊,所以我把它作为挑战。但请记住,如果它刚刚粘贴,那么这个例子将工作,因为它根本不是模块化的,这个有限的例子有你需要的缺陷手动刷新页面以查看效果:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Last Visited Test</title>

    <style>
        /* What visited links should look like */
        .lastVisitedLink {
            color: purple;
            border: 1px groove black;
        }

        /* What all other links should look like */    
        a:not(.lastVisitedLink) {
            color: blue;
        }
    </style>
</head>
<body>
    <ul>
        <li><a href="#a">Link 1</a></li>
        <li><a href="#b">Link 2</a></li>
        <li><a href="#c">Link 3</a></li>
        <li><a href="#d">Link 4</a></li>
    </ul>

    <script>
        var localStorageKey = 'lastVisitedLinkSave';

        var links = document.getElementsByTagName('a');

        //Since "links" is a nodeList, not an array
        Array.prototype.forEach.call(links, function(link) {
            var lastClicked = localStorage.getItem(localStorageKey);

            if (lastClicked === link.href) {
                link.className = 'lastVisitedLink';

            } else {
                link.className = '';
            }

            link.onclick = function(event) {
                event.preventDefault();

                localStorage.setItem(localStorageKey, this.href);

                this.className = 'lastVisitedLink';

                location.href = this.href;
            }
        });
    </script>
</body>
</html>

CSS类lastVisitedLink定义了您希望访问过的链接的外观。该类将添加到最后单击的链接中。显然,在真实的网站中,这将在外部而非内部定义。

这是关键部分:

//Find all anchor(link) tags
var links = document.getElementsByTagName('a');

//Using the prototype since "links" is a nodeList, not an array
//Here, we're going over all the links found on the page.
//For each link, we're checking if it's the last clicked link. If it is, add the CSS class to it to style it. If it's not the last clicked, remove all other classes associated with it.
Array.prototype.forEach.call(links, function(link) {
    var lastClicked = localStorage.getItem(localStorageKey);

    if (lastClicked === link.href) {
        link.className = 'lastVisitedLink';

    } else {
        link.className = '';
    }

    //Whenever a link is clicked, we save it as the last clicked link (to local storage), set the class name (same as above), then have the link change the page as usual.
    link.onclick = function(event) {
        event.preventDefault();

        localStorage.setItem(localStorageKey, this.href);

        this.className = 'lastVisitedLink';

        location.href = this.href;
    }
});

我在5分钟内写了这篇文章,所以它远非完美。如评论中所述,如果该链接不是最后一次点击,则会删除与该链接相关联的所有其他类。如果您只想删除lastClickedLink类,则需要更复杂的解决方案,因为AFAIK,vanilla JavaScript没有简单的方法来执行此操作。

您还需要对localStorage有一个基本的了解才能正确使用它。它是将数据保存到客户端计算机的便捷工具。