如何使用 JavaScript 檢測螢幕解析度?
要檢測螢幕解析度,請使用 window.screen 概念。
對於寬度,請使用以下內容 −
window.screen.availWidth
對於高度 −
window.screen.availHeight
以下是檢測螢幕解析度的程式碼 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <script> console.log("Available Width="+window.screen.availWidth); console.log("Available Height="+window.screen.availHeight); </script> </body> </html>
要執行上述程式,請儲存檔名“anyName.html(index.html)”並右鍵單擊該檔案。在 VS Code 編輯器中選擇“用 Live Server 開啟”選項。
輸出
這將產生以下輸出 −
廣告