LoginSignup
2
3

More than 5 years have passed since last update.

疑似クラスvisitedをlocalStorageを使って装飾する

Last updated at Posted at 2016-12-13

擬似クラスvisitedはプライバシー上の理由で、特定のプロパティ(色に関するもの)しか利用できません。
:visited - CSS | MDN

私がやりたかったのはアイコンフォントを使ってチェックマークをbeforeを使い、未訪問と訪問済みで使い分けたかったのです。
こんな感じ↓
訪問.png

しかしvisitedは擬似クラスにも対応していません。

a:visited:before {
    content: "これは適用されません";
}

この問題に解決するためにクッキーで訪問の判別をする方法が出回ってました。
「ライブラリ入れるの面倒くさい」
「リクエストが増えるのが嫌だ」
ということでlocalStorageを使ってみました。

コード

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>タイトル</title>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css">
<body>


<ul>
  <li><a href="//localhost:3000/test/">未訪問</a></li>
  <li><a href="//localhost:3000/">訪問済み</a></li>
</ul>



<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</body>
</html>
style.scss
ul {
  list-style: none;
}
a {
  &:before {
    content: "\f096";
    font-family: "FontAwesome";
    margin-right: 0.5em;
  }
  &.visited {
    &:before {
      content: "\f046";
    }
  }
}
style.css
ul {
  list-style: none;
}

a:before {
  content: "\f096";
  font-family: "FontAwesome";
  margin-right: 0.5em;
}

a.visited:before {
  content: "\f046";
}
script.js(jQuery)
$(function(){
  var nowLocation = location.href;
  localStorage.setItem(nowLocation, nowLocation);

  $('a').each(function(){
    var anchorHref = $(this).prop('href');
    var anchorHref = anchorHref.replace(/(index.html|index.php)/gi,'');
    if( localStorage.getItem(anchorHref) == anchorHref ){
      $(this).addClass('visited');
    }
  });
});

仕組み

location.hrefで現在のURLを取得します。
location.hreflocalStorageに入れます。訪れたページが全てlocalStorageに入ってます。
aの数だけループします。
$(this).prop('href');でhrefの値を拾い、anchorHref.replaceで表記のばらつきを直します。
直したhrefの値がlocalStorageの中にあればclass="visited"を追加して完了。

解決できないこと

外部サイトはデータを保存出来ないので判別できません。
割りとそこがネックなのですが、今回は私が使用したものでは問題になりませんでした。

HTML5に対応していないブラウザはlocalStorageを使えません。また、一部環境では容量に制限があります(数量は無制限)。

一部環境でプライベートブラウジング時はうまく動きません。
SafariのプライベートブラウジングでWebStorageが使用できない挙動と対処法

最後

visitedが色だけしか変更できないのを知っていて無理やり脳が忘れたみたいです。
些細なことだったのですが、モヤモヤした気持ちになったので適用させてみました。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3