js实现响应式布局
使用 CSS Media Queries
响应式布局的核心是CSS媒体查询(Media Queries),通过检测视口宽度动态调整样式。在HTML中引入以下CSS代码:
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
动态 Viewport 设置
在HTML的<head>中添加viewport元标签,确保移动设备正确缩放:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
JavaScript 监听窗口变化
通过window.addEventListener监听resize事件,实时获取窗口尺寸并执行相应操作:
window.addEventListener('resize', function() {
const width = window.innerWidth;
if (width < 768) {
document.body.style.fontSize = '14px';
} else {
document.body.style.fontSize = '16px';
}
});
动态加载资源
根据屏幕尺寸条件加载不同资源:
function loadResponsiveResources() {
const screenWidth = window.innerWidth;
const script = document.createElement('script');
if (screenWidth < 768) {
script.src = 'mobile.js';
} else {
script.src = 'desktop.js';
}
document.body.appendChild(script);
}
loadResponsiveResources();
window.addEventListener('resize', loadResponsiveResources);
图片响应式处理
使用<picture>元素或JavaScript动态切换图片源:
<picture>
<source media="(max-width: 600px)" srcset="small.jpg">
<source media="(min-width: 601px)" srcset="large.jpg">
<img src="fallback.jpg" alt="Responsive image">
</picture>
或通过JavaScript控制:
function updateImages() {
const images = document.querySelectorAll('[data-responsive]');
images.forEach(img => {
const newSrc = window.innerWidth < 768
? img.dataset.mobile
: img.dataset.desktop;
img.src = newSrc;
});
}
响应式字体大小
使用CSS的clamp()函数或JavaScript动态计算字体大小:
function setResponsiveFontSize() {
const baseSize = 16;
const scale = window.innerWidth / 1200;
const fontSize = Math.max(baseSize, Math.min(baseSize * scale, 20));
document.documentElement.style.fontSize = `${fontSize}px`;
}
断点管理
创建统一的断点管理对象,提高代码可维护性:
const breakpoints = {
sm: 576,
md: 768,
lg: 992,
xl: 1200
};
function checkBreakpoint() {
const currentWidth = window.innerWidth;
if (currentWidth < breakpoints.sm) {
console.log('Extra small devices');
} else if (currentWidth < breakpoints.md) {
console.log('Small devices');
}
}
性能优化
使用防抖技术优化resize事件处理:
function debounce(func, wait) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(func, wait);
};
}
window.addEventListener('resize', debounce(function() {
console.log('Resize handler after 250ms delay');
}, 250));






