web-dev-qa-db-ja.com

アンカータグにプログラムでスクロールする

次のコードを検討してください。

<a href="#label2">GoTo Label2</a>
... [content here] ...
<a name="label0"></a>More content
<a name="label1"></a>More content
<a name="label2"></a>More content
<a name="label3"></a>More content
<a name="label4"></a>More content

「GoTo Label2」リンクをクリックして、コードを介してページ上の適切な領域にスクロールするエミュレートする方法はありますか?

[〜#〜] edit [〜#〜]:受け入れられる代替手段は、ページにすでに存在するunique-idを持つ要素にスクロールすることです。これが実行可能なソリューションである場合、アンカータグを追加します。

43
Anders

このJSは、要素にIDを追加した場合、一般的にうまく機能しました。

document.getElementById('MyID').scrollIntoView(true);

これは、コンテンツが表示されるようにスクロール可能なdivなども配置するので便利です。

73
MikeeMike

JavaScriptを使用:

window.location.href = '#label2';

サーバー/コードビハインドから実行する必要がある場合は、このJavascriptを発行して、そのページのスタートアップスクリプトとして登録するだけです。

11
CubanX

サーバー側からアンカーに移動する例は、c#です。

ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);
3
Gareth Williams

私はこれがうまくいくと思う:

window.location="<yourCurrentUri>#label2";
2
mkoeller

ソリューション

document.getElementById('MyID').scrollIntoView(true);

ほぼすべてのブラウザーでうまく機能しますが、一部のブラウザーまたは一部のモバイル(一部のBlackberryバージョンなど)では「scrollIntoView」機能が認識されないことに気付きました。そのため、このソリューションを検討します(以前のものより少しbitい) :

window.location.href = window.location.protocol + "//" + window.location.Host + 
                       window.location.pathname + window.location.search + 
                       "#MyAnchor";
1
sebarmeli

要素がアンカータグの場合、次のことができるはずです。

document.getElementsByName('label2')[0].focus();
1
tvanfosson

名前を追加して新しいURLを開くことができます。たとえば、http://www.example.com/mypage.htm#label2

JavaScriptでは、

location.href = location.href + '#label2';
0
Ken Pespisa

window.location.hashを使用する場合、「#」はありません

0
DannyR