2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Wordpress向け】現在のページへのリンクを無効化して、スタイルを変える

Last updated at Posted at 2016-03-29

Wordpress向けです。

仕様

構造が同じページが複数ある。
サイドバーにそれらのページへのリンク一覧がある。
テンプレートは複数作らずに、ページ内にある現在のページへのリンクを無効にして背景色をつけるなどスタイルを変えたい。

HTML

http://piyo.jp/hogehoge/kuma/
http://piyo.jp/hogehoge/tama/
http://piyo.jp/hogehoge/kiso/
という三つのページがある想定で進めます。

HTML
<section>
   <h2>KUMAGATA</h2>
   <ul>
      <li><a href="../kuma" data-trigger="trigger">球磨</a></li>
      <li><a href="../tama" data-trigger="trigger">多摩</a></li>
      <li><a href="../kiso" data-trigger="trigger">木曽</a></li>
    </ul>
</section>

というサイドバーがあるとします。

js
var temp = function(){
	var $target = $('[data-trigger]'),  //サイドバーにあるリンク達
		url = window.location.href,  //現在のページのurl
		before = /(http[\s\S\w]*?\/hogehoge\/)/,  //'http'から'hogehoge/'までを指定
		after = /(\/)/,  //url最後の'/'を指定
		$trigger = url.replace(before, '').replace(after, ''),  //現在のページurl文字列から上記のbeforeとafterを削除
		compare_fnc = function($target,other,current){
			var $target_url = $target.attr('href'),  //サイドバーにあるリンクのurl
				before = /(\.\.)/,  //'../'を指定
				after = /(\/)/,  //url最後の'/'を指定
				$target_url_r = $target_url.replace(before, '').replace(after, '');  //サイドバーにあるリンクのurl文字列から上記のbeforeとafterを削除
			if($target_url_r == $trigger) {  //現在のページurlとリンク先が同じtargetに対して以下の動作を実行
				$target.removeClass(other).addClass(current);  //引数otherに指定したクラスを削除し、引数currentに指定したクラスを追加
				$target.on('click',function(){
					return false;  //リンク機能を停止
				});
			}
		};
	if(!$target.length) return;  //targetが無い場合return
	$target.each(function(){  //eachでcompare_fncを回す
		compare_fnc($(this),'primary_btn','primary_btn-on');
	});
};

まとめ

wordpress使うのやめたい

2
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?