狙った位置までスクロールする方法
HTMLで縦に長いページの場合、自動的にスクロールされると見やすいです。
JavaScriptを使います。
目次
一番下までスクロールする方法
document.documentElement.scrollTopにピクセルを指定するとそこまでスクロールします。
ドキュメントの高さから画面の高さを引いた高さまでスクロールすれば一番下までスクロールすることになります。
scroll_bottom();
function scroll_bottom(){
const element = document.documentElement;
const bottom = element.scrollHeight - element.clientHeight;
document.documentElement.scrollTop = bottom;
}
function scroll_bottom(){
const element = document.documentElement;
const bottom = element.scrollHeight - element.clientHeight;
document.documentElement.scrollTop = bottom;
}
一番下までスクロールするずぼらな方法
一番下までスクロールするだけならば適当に大きな数値を指定すればいいです。
またwindow.scroll(x, y)を使う方法もあります。
window.scroll(0, 10000);
任意の位置までスクロールする方法
任意の位置が、要素のidで指定できる場合に使えます。
これは結構、複雑です。
getBoundingClientRectで要素のサイズを長方形で取得します。
topで画面の上からの長さを取得します。
window.pageYOffsetでドキュメントの画面より上の長さを取得します。
rect.top+window.pageYOffsetで要素の上の位置を取得できます。
scroll_id("x3");
function scroll_id(id) {
const element = document.getElementById(id);
const rect = element.getBoundingClientRect();
const element_top = rect.top + window.pageYOffset;
document.documentElement.scrollTop = element_top;
}
function scroll_id(id) {
const element = document.getElementById(id);
const rect = element.getBoundingClientRect();
const element_top = rect.top + window.pageYOffset;
document.documentElement.scrollTop = element_top;
}
[ 2023年5月11日 | カテゴリー: JavaScript | タグ: scroll ]
コメントを残す