:target
:targetはハッシュフラグメントにより絞り込みが行うことができるセレクタです。
このセレクタによりハッシュフラグメントと同じidをもつ要素のjQueryオブジェクトが取得できます。
次のようなHTMLがあったとします。
<style>
.target{
color:red;
}
</style>
<div id="target1">#target1</div>
<div id="target2">#target2</div>
ハッシュフラグメントが#target1の場合は「<div id=”target1″>#target1</div>」を、ハッシュフラグメントが#target2の場合は「<div id=”target1″>#target2</div>」を指定することができます。
$(":target").addClass("target");
ただ、ブラウザによりこのセレクタが利用できるようになるまで若干のタイムラグがあります(jQuery1.9.0時点)。
Firefox(17.0.1)ではDOM ready後に:targetが利用できるようになります。
$(function(){
$(":target").addClass("target");
});
sample(#target1) / sample(#target2)
Google Chrome( 24.0.1312.52)ではwindow load後に1ms以上まってから指定する必要があります。(リロード時やキャッシュされている場合は1ms待たなくてもよい)
$(window).on("load",function(){
setTimeout(function(){
$(":target").addClass("target");
},1);
});
sample(#target1) / sample(#target2)
その為、:targetは利用せずJavaScriptのlocation.hashによりid名を取得したほうがよいでしょう。
jQuery 1.9.0での追加/変更:targetはCSS3で定義されているセレクタのためCSS3対応ブラウザでは古いバージョンのjQueryから利用できますが、jQuery 1.9.0でjQueryのSizzleエンジンに追加されCSS3未対応ブラウザでも利用可能になりました。
参考URL
:target Selector | jQuery API Documentation
登録日 : 2013年01月19日 最終更新日 : 2013年1月19日
同じカテゴリー(Selectors)のエントリー
- :disabled
- [attribute~=’value’]
- [attribute|=’value’]
- :animated
- :focus
- :target
- :lang()
- :root
- :only-of-type
- :last-of-type
- :first-of-type
- :nth-last-of-type()
- :nth-of-type()
- :nth-last-child()
- :selected
- :checked
- :file
- :button
- :reset
- :image
- :submit
- :checkbox
- :radio
- :password
- :text
- :input
- :parent
- :has()
- :contains()
- :header
- :lt()
- :gt()
- :eq()
- :odd
- :even
- :last
- :first
- [attributeFilter1][attributeFilter2]
- [attribute*=’value’]
- [attribute$=’value’]
- [attribute^=’value’]
- [attribute!=’value’]
- [attribute=’value’]
- [attribute]
- :not()
- :empty
- :only-child
- :last-child
- :first-child
- 兄弟セレクタ
- 隣接セレクタ
- 子セレクタ
- 子孫セレクタ
- グループセレクタ
- classセレクタ
- idセレクタ
- 要素セレクタ
- ユニバーサルセレクタ