■js
jQuery(function() {
var pages = jQuery('.section');
pages.hide();
if ( location.hash ) {
jQuery('html,body').scrollTop(0);
jQuery(location.hash).fadeIn();
} else {
pages.eq(0).fadeIn();
}
jQuery('.tab a').click(function(event){
event.preventDefault();
var nextPage = this.hash;
pages.hide();
jQuery(nextPage).fadeIn();
});
});
■HTML
<ul class="tab">
<li><a href="aaa#home"></li>
<li><a href="aaa#contact"></li>
</ul>
<div id="home" class="section"></div>
<div id="contact" class="section"></div>
現在の仕様としましては、
・タブをクリックしてもURLに#○○がつかない
・外部から直接 URL#○○にアクセスできる
となっていますが、要望としては、
・タブをクリックしてもURLに#○○がつかない(同じ)
・タブをクリックした際に、タブにクラス(current)を付ける
・外部から直接 URL#○○にアクセスできるが、URL表示には#○○がつかない
になります。
最後のURL表示については、そもそも無理な可能性があるのでスルーしていただいて、タブのクラス付けだけでも回答いただきたいと思います。どうぞよろしくお願いします。
こんな感じでどうでしょう。
jQuery(function() { var pages = jQuery('.section'); var target = location.hash; pages.hide(); if ( target ) { jQuery('html,body').scrollTop(0); jQuery(target).fadeIn(); // location.hash = ""; ★ハッシュ消しても、中途半端 (´・ω・`) jQuery('.tab li a[href="'+ target + '"]').attr("class", "current"); } else { pages.eq(0).fadeIn(); jQuery('.tab li a').eq(0).attr("class", "current"); } jQuery('.tab a').click(function(event){ event.preventDefault(); jQuery('.tab li a').attr("class", ""); jQuery(this).attr("class", "current"); var nextPage = this.hash; pages.hide(); jQuery(nextPage).fadeIn(); }); });
URL の # が残っちゃいますが、これを消すと home に飛んじゃいます...
HTML は、こんな感じ。
<ul class="tab"> <li><a href="#home">home</a></li> <li><a href="#contact">contact</a></li> <li><a href="#etc">etc</a></li> </ul> <div id="home" class="section">home</div> <div id="contact" class="section">contact</div> <div id="etc" class="section">etc</div> <style> .current { background-color: pink; } </style>
jsFiddle で試してみたのが、こちらです(ハッシュ付きで呼び出したときの動作が確認できませんが)。
http://jsfiddle.net/1e6g2qrt/