jQuery resizeメソッドを使って画面サイズを取得するサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

構文
1.幅を取得します
$(window).width()
2.高さを取得します。
$(window).height()
3.画面のサイズ変更のイベント
$(window).resize(function () {処理コード}
resizeメソッドを使って、画面のサイズ変更時にサイズを取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//画面のサイズ変更
$(window).resize(function () {
let w = $(window).width()
let h = $(window).height()
$('#result').text(`画面の幅: ${w} 画面の高さ:${h}`)
})
});
</script>
</head>
<body>
<h2 id="result"></h2>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ //画面のサイズ変更 $(window).resize(function () { let w = $(window).width() let h = $(window).height() $('#result').text(`画面の幅: ${w} 画面の高さ:${h}`) }) }); </script> </head> <body> <h2 id="result"></h2> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
 //画面のサイズ変更
    $(window).resize(function () {

    let w = $(window).width()
    let h = $(window).height()
    $('#result').text(`画面の幅: ${w} 画面の高さ:${h}`)

  })
});
</script>
</head>
<body>
 <h2 id="result"></h2>
 </body>
</html>

実行結果
画面のサイズを変更して幅と高さを表示します。

jQuery

Posted by arkgame