js实现视口
获取视口尺寸
通过 window.innerWidth 和 window.innerHeight 获取当前视口的宽度和高度(包含滚动条):
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
若需排除滚动条宽度,使用 document.documentElement.clientWidth 和 clientHeight:

const noScrollbarWidth = document.documentElement.clientWidth;
const noScrollbarHeight = document.documentElement.clientHeight;
监听视口变化
通过 resize 事件监听视口尺寸变化,并使用防抖优化性能:
function debounce(fn, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, arguments), delay);
};
}
window.addEventListener('resize', debounce(() => {
console.log(`New viewport size: ${window.innerWidth}x${window.innerHeight}`);
}, 300));
检测移动设备视口
结合 window.screen.width 和 window.orientation 判断移动设备横竖屏:

const isMobilePortrait = window.innerWidth < window.innerHeight &&
window.screen.width < 768;
const isMobileLandscape = window.innerWidth > window.innerHeight &&
window.screen.width >= 768;
设置视口 Meta 标签
通过 JavaScript 动态修改 <meta name="viewport"> 内容:
const metaViewport = document.querySelector('meta[name="viewport"]');
metaViewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0');
视口相关 CSS 单位转换
将视口单位(vw/vh)转换为像素值:
function vwToPixels(vw) {
return (vw * window.innerWidth) / 100;
}
function vhToPixels(vh) {
return (vh * window.innerHeight) / 100;
}






