js实现适配
实现响应式布局的方法
使用CSS媒体查询结合JavaScript动态调整布局。媒体查询负责基础样式适配,JavaScript处理更复杂的交互逻辑。
@media (max-width: 768px) {
.container {
width: 100%;
}
}
function checkScreenSize() {
const width = window.innerWidth;
if (width < 768) {
// 移动端逻辑
} else {
// 桌面端逻辑
}
}
window.addEventListener('resize', checkScreenSize);
动态REM方案
通过设置根元素字体大小实现等比缩放。计算基准值并监听窗口变化自动调整。
function setRemUnit() {
const docEl = document.documentElement;
const width = docEl.clientWidth;
const rem = width / 10;
docEl.style.fontSize = rem + 'px';
}
setRemUnit();
window.addEventListener('resize', setRemUnit);
视口单位适配
使用vw/vh单位配合calc()实现弹性布局。结合CSS变量提升可维护性。

:root {
--vw: 1vw;
}
.box {
width: calc(var(--vw) * 50);
height: calc(100vh - 10rem);
}
图片自适应处理
根据设备像素比选择合适图片资源。使用srcset属性或JavaScript动态替换。
<img src="default.jpg"
srcset="small.jpg 480w, medium.jpg 768w"
sizes="(max-width: 600px) 480px, 800px">
组件级适配策略
针对复杂组件实现差异化渲染。通过条件判断加载不同组件版本。

const Component = window.innerWidth > 1024
? DesktopComponent
: MobileComponent;
ReactDOM.render(<Component />, container);
触摸事件优化
为移动设备添加触摸反馈。同时考虑桌面端的鼠标事件兼容。
element.addEventListener('touchstart', handleTouch, {passive: true});
element.addEventListener('click', handleClick);
性能优化措施
实现懒加载和资源按需加载。监控DOM变化时使用防抖技术。
const lazyLoad = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
lazyLoad.unobserve(entry.target);
}
});
});
document.querySelectorAll('[data-src]').forEach(img => {
lazyLoad.observe(img);
});






