window.locationオブジェクトページ内移動(アンカー)、指定したURLへ移動
- 現在のURLの#以降のアンカー名を取得〔hashプロパティ〕
- ページ内の指定したアンカー名へ移動〔hashプロパティ〕
- 現在のページのURLを取得〔hrefプロパティ〕
- 指定したURLへ移動〔hrefプロパティ〕
現在のURLの#以降のアンカー名を取得
hashプロパティ
unknown
window.location.hash
オブジェクト名windowは省略可。
サンプルを見る
<script type="text/javascript"> document.write("現在のURL:<em>"+location.href+"<\/em><br \/>"); document.write("現在のURLの#以降のアンカー名:<em>"+location.hash+"<\/em>"); </script>
ページ内の指定したアンカー名へ移動
hashプロパティ
unknown
window.location.hash = "アンカー名"
移動先となる場所には、<a name="アンカー名"></a>
のように、a要素のname属性にアンカー名を指定します。
例えば、ページの先頭に<a name="pagetop"></a>
と記述しておくと、ページの要所要所で
<a href="#" onClick="location.hash='pagetop'; return false;">先頭へ</a>
と記述したリンクをクリックすれば、ページの先頭へジャンプさせることができます。
このhashプロパティを使用せずに、<a href="#pagetop">先頭へ</a>
と記述しても同様にページの先頭にジャンプさせることができます。
オブジェクト名windowは省略可。
サンプルを見る<a name="pagetop">-------------------------ページの先頭です-------------------------</a> <br> <p> ▼<br> ▼<br> ▼<br> ページの最下部に、スクリプトがあります ▼<br> ▼<br> ▼<br> </p> <script type="text/javascript"> for(var i=0; i<=100; i++){ document.write("<br \/>"); } </script> <a href="#" onclick="location.hash='';location.hash='pagetop';return false;">ページの先頭へ(hashプロパティ使用)</a> <br> <a href="#pagetop">ページの先頭へ(hashプロパティ不使用)</a>
現在のページのURLを取得
hrefプロパティ
unknown
window.location.href
オブジェクト名windowは省略可。
サンプルを見る<script type='text/javascript'> document.write("現在のページのURL:<em>"+location.href+"<\/em>"); //http://localhost/test/pj_roomer/index.php?t=js&p=21#1 </script>
指定したURLへ移動
hrefプロパティ
unknown
window.location.href = URL
location.hrefプロパティを手動で設定し、指定したURLにジャンプさせることができます。
オブジェクト名windowは省略可。
サンプルを見る<script type="text/javascript"> function urlJump(){ var w = window.open("http://www.infoseek.co.jp/"); if(confirm("Googleに移動しますか?" )){ /* [OK]ボタンが押されたら(TRUE)、Googleへジャンプ */ w.location.href = "http://www.google.co.jp/"; }else{ /* [キャンセル]ボタンがされたら(FALSE)、Bingへジャンプ */ w.location.href = "https://www.bing.com/"; } w.focus(); } </script> <form action="#"> <input type="button" value="ジャンプ" onclick="urlJump()" /> </form>