控制螢幕顯示大小
程式置於<script></script>之間,<body>之前。
一、以像素調整
// 偵測螢幕解析度
var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// 設定目標解析度
var targetWidth = 1366;
var targetHeight = 768;
// 確認是否需要進行切割
if (screenWidth > targetWidth || screenHeight > targetHeight) {
// 計算切割比例
var scale = Math.min(targetWidth / screenWidth, targetHeight / screenHeight);
// 設定畫面限制大小
var limitedWidth = Math.round(screenWidth * scale);
var limitedHeight = Math.round(screenHeight * scale);
// 設定畫面居中
var offsetX = Math.floor((screenWidth - limitedWidth) / 2);
var offsetY = Math.floor((screenHeight - limitedHeight) / 2);
// 設定畫面樣式
document.body.style.overflow = 'hidden';
document.body.style.width = limitedWidth + 'px';
document.body.style.height = limitedHeight + 'px';
document.body.style.margin = offsetY + 'px ' + offsetX + 'px';
}
二、以百分比調整
// 偵測螢幕解析度
var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var screenHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// 設定畫面限制大小
var maxWidth = 1280;
var maxHeight = 768;
// 檢查螢幕解析度是否大於限制大小,如果是,就調整畫面大小
if (screenWidth > maxWidth || screenHeight > maxHeight) {
// 計算縮放比例
var scale = Math.min(maxWidth / screenWidth, maxHeight / screenHeight);
// 設定 body 的 CSS 樣式,進行縮放
document.body.style.transformOrigin = "top left";
document.body.style.transform = "scale(" + scale + ")";
document.body.style.width = (100 / scale) + "%";
document.body.style.height = (100 / scale) + "%";
// 設定 body 的 CSS 樣式,進行縮放的程式碼...
// 新增水平且垂直置中的程式碼
document.body.style.display = "flex";
document.body.style.justifyContent = "center";
document.body.style.alignItems = "center";
}