// main.js (或者你项目的入口文件)
const mobileMediaQuery = window.matchMedia(‘(max-width: 767px)’);
const desktopMediaQuery = window.matchMedia(‘(min-width: 768px)’);
const applyCSS = (mediaQuery, cssPath) => {
if (mediaQuery.matches) {
const link = document.createElement(‘link’);
link.rel = ‘stylesheet’;
link.href = cssPath;
document.head.appendChild(link);
}
};
applyCSS(mobileMediaQuery, ‘/path/to/mobile.css’);
applyCSS(desktopMediaQuery, ‘/path/to/desktop.css’);
// 监听屏幕尺寸变化,动态应用样式
mobileMediaQuery.addListener(() => {
if (mobileMediaQuery.matches) {
const link = document.createElement(‘link’);
link.rel = ‘stylesheet’;
link.href = ‘/path/to/mobile.css’;
document.head.appendChild(link);
}
});
desktopMediaQuery.addListener(() => {
if (desktopMediaQuery.matches) {
const link = document.createElement(‘link’);
link.rel = ‘stylesheet’;
link.href = ‘/path/to/desktop.css’;
document.head.appendChild(link);
}
});