ウィンドウサイズの取得
表示領域のサイズ
document.documentElement.clientWidth
document.documentElement.clientHeight
スクロール位置
// Chrome以外のブラウザで解釈される
document.documentElement.scrollTop
document.documentElement.scrollLeft
// Chromeで解釈される
document.body.scrollTop
document.body.scrollLeft
コンテンツのサイズ
obj.scrollHeight
obj.scrollWidth
ドキュメントのサイズ
// IE10以下で互換性の問題が発生する可能性あり
document.documentElement.offsetWidth
document.documentElement.offsetHeight
// こちらの方法が推奨される
document.body.offsetWidth
document.body.offsetHeight
実装例
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ウィンドウサイズの取得</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
// 表示領域の幅を取得
const viewportWidth = document.documentElement.clientWidth;
console.log('表示領域の幅: ' + viewportWidth + 'px');
// スクロール位置を取得(クロスブラウザ対応)
document.addEventListener('click', function() {
const scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
console.log('スクロール位置: ' + scrollPosition + 'px');
});
// コンテンツの高さを取得
const contentElement = document.getElementById("contentArea");
const contentHeight = contentElement.scrollHeight;
console.log('コンテンツの高さ: ' + contentHeight + 'px');
// ドキュメントの高さを取得(推奨方法)
const docHeight = document.body.offsetHeight;
console.log('ドキュメントの高さ: ' + docHeight + 'px');
});
</script>
</head>
<body>
<div id="contentArea" style="width:100px;height:100px;border:1px solid red;padding:10px;margin:10px;">
<div id="innerContent" style="width:100px;height:200px;background-color:pink;"></div>
</div>
</body>
</html>
ウィンドウイベント
スクロールイベント
onscroll スクロールバーがスクロールしたときにトリガーされます。
リサイズイベント
onresize ウィンドウサイズが変更されたときにトリガーされます。
イベント処理の実装例
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ウィンドウイベントの処理</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
let scrollPosition = null;
// スクロールイベントの処理
window.addEventListener('scroll', function() {
scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
console.log('現在のスクロール位置: ' + scrollPosition + 'px');
});
let currentWidth = null;
// リサイズイベントの処理
window.addEventListener('resize', function() {
currentWidth = document.documentElement.clientWidth;
console.log('現在の表示領域の幅: ' + currentWidth + 'px');
});
});
</script>
</head>
<body style="height:2000px">
<p>ページをスクロールまたはウィンドウのサイズを変更してみてください。</p>
</body>
</html>