如何使用JavaScript通过trackbar调整网页窗口的尺寸
滑块控制网页窗口尺寸实现方案
你可以直接基于你现有尺寸显示的逻辑,补充滑块元素和事件绑定即可,完整实现代码如下:
<!DOCTYPE html> <html> <body> <!-- 宽度控制滑块 --> <div> 窗口宽度控制:<input type="range" id="widthTrack" min="300" max="1920" value="800"> <span id="widthVal">800</span>px </div> <!-- 高度控制滑块 --> <div> 窗口高度控制:<input type="range" id="heightTrack" min="200" max="1080" value="600"> <span id="heightVal">600</span>px </div> <!-- 尺寸显示区域 --> <div id="show"></div> <script> // 你原有窗口尺寸显示逻辑,仅做了格式优化 function displayWindowInner() { var W = window.innerWidth; var H = window.innerHeight; var x = document.getElementById("show"); x.innerHTML = "当前窗口尺寸:宽度:" + W + "px,高度:" + H + "px"; } // 页面加载时初始化尺寸显示 displayWindowInner(); // 窗口尺寸变化时自动更新显示 window.addEventListener('resize', displayWindowInner); // 滑块控制逻辑 const widthTrack = document.getElementById('widthTrack'); const heightTrack = document.getElementById('heightTrack'); const widthVal = document.getElementById('widthVal'); const heightVal = document.getElementById('heightVal'); // 宽度滑块事件绑定 widthTrack.addEventListener('input', () => { const targetWidth = widthTrack.value; widthVal.innerText = targetWidth; // 调整窗口宽度,高度保留当前值 window.resizeTo(targetWidth, window.outerHeight); }) // 高度滑块事件绑定 heightTrack.addEventListener('input', () => { const targetHeight = heightTrack.value; heightVal.innerText = targetHeight; // 调整窗口高度,宽度保留当前值 window.resizeTo(window.outerWidth, targetHeight); }) </script> </body> </html>
注意事项
- 受浏览器安全策略限制,
window.resizeTo方法仅对通过window.open方法打开的窗口生效,普通用户手动打开的页面,多数浏览器会禁止该操作,避免恶意篡改用户窗口大小。 - 你可以自行修改滑块
input标签的min、max属性,调整可控制的尺寸范围。
内容的提问来源于stack exchange,提问作者Ayoub Ali
相关产品推荐
相关产品推荐

