jQueryを使用してページ上の特定の場所にスクロールすることは可能ですか?
スクロールしたい場所には次のものが必要ですか?
<a name="#123">here</a>
それとも、特定の DOM ID に移動できますか?
jQueryを使用してページ上の特定の場所にスクロールすることは可能ですか?
スクロールしたい場所には次のものが必要ですか?
<a name="#123">here</a>
それとも、特定の DOM ID に移動できますか?
jQueryスクロールプラグイン
これはjqueryでタグ付けされた質問であるため、このライブラリにはスムーズなスクロールのための非常に優れたプラグインがあるため、ここで見つけることができます:http: //plugins.jquery.com/scrollTo/
ドキュメントからの抜粋:
$('div.pane').scrollTo(...);//all divs w/class pane
また
$.scrollTo(...);//the plugin will take care of this
スクロール用のカスタムjQuery関数
カスタムスクロールjquery関数を定義することにより、非常に軽量なアプローチを使用できます
$.fn.scrollView = function () {
return this.each(function () {
$('html, body').animate({
scrollTop: $(this).offset().top
}, 1000);
});
}
次のように使用します。
$('#your-div').scrollView();
ページ座標までスクロール
または属性を持つ要素をアニメーションhtml
化するbody
scrollTop
scrollLeft
$('html, body').animate({
scrollTop: 0,
scrollLeft: 300
}, 1000);
プレーンJavaScript
でスクロールwindow.scroll
window.scroll(horizontalOffset, verticalOffset);
要約すると、window.location.hashを使用してIDを持つ要素にジャンプします
window.location.hash = '#your-page-element';
HTMLで直接(アクセス性の強化)
<a href="#your-page-element">Jump to ID</a>
<div id="your-page-element">
will jump here
</div>
うん、普通の JavaScript でもとても簡単です。要素に id を指定すると、それを「ブックマーク」として使用できます。
<div id="here">here</div>
ユーザーがリンクをクリックしたときにそこにスクロールしたい場合は、実証済みの方法を使用できます。
<a href="#here">scroll to over there</a>
プログラムでそれを行うには、使用しますscrollIntoView()
document.getElementById("here").scrollIntoView()
純粋なJavaScriptバージョンは次のとおりです。
location.hash = '#123';
自動的にスクロールします。「#」プレフィックスを追加することを忘れないでください。
プレーン Javascript:
window.location = "#elementId"
<div id="idVal">
<!--div content goes here-->
</div>
...
<script type="text/javascript">
$(document).ready(function(){
var divLoc = $('#idVal').offset();
$('html, body').animate({scrollTop: divLoc.top}, "slow");
});
</script>
この例は、特定の div id、つまりこの場合は 'idVal' を検索する方法を示しています。このページで ajax を介して開く後続の div/テーブルがある場合は、一意の div を割り当て、スクリプトを呼び出して、div の各コンテンツの特定の場所にスクロールできます。
これが役立つことを願っています。
これを試して
<div id="divRegister"></div>
$(document).ready(function() {
location.hash = "divRegister";
});
これは、@juraj-blahunka の軽量アプローチの変形です。この関数は、コンテナーがドキュメントであると想定せず、アイテムが表示されていない場合にのみスクロールします。不必要なバウンスを避けるために、アニメーションのキューイングも無効になっています。
$.fn.scrollToView = function () {
return $.each(this, function () {
if ($(this).position().top < 0 ||
$(this).position().top + $(this).height() > $(this).parent().height()) {
$(this).parent().animate({
scrollTop: $(this).parent().scrollTop() + $(this).position().top
}, {
duration: 300,
queue: false
});
}
});
};
scroll-behavior: smooth;
Javascriptなしでこれを行うために使用できます
https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior