我正在尝试使用 Javascript 检查屏幕尺寸。 我的元素将根据屏幕的大小以不同的方式呈现动画。
我认为我离结果不太远,但还没有真正完全理解它。
当我加载页面时,无论窗口大小如何,console.log 都会出现两次。
通过手动缩小窗口,通过拖动鼠标,有: - 2 console.log('MD') 当 MD 的大小合适时 - 1 console.log('SM') 当 SM 大小合适时
通过手动放大窗口,通过拖动鼠标,有: - 1 console.log('MD') 当 MD 的大小合适时 - 1 console.log('SM') 当 LG 的尺寸合适时 - 1 console.log('LG') 当 LG 的大小合适时
但是通过使用浏览器图标调整窗口的大小,我的console.log如我所愿。
可以再解释一下吗?
我希望我已经说清楚了。
let mqls = [
window.matchMedia('screen and (min-width: 768px) and (max-width: 991px'),
window.matchMedia('screen and (min-width: 992px)')
];
function test(mql){
if( mqls[0].matches ){
console.log('MD')
}
else if( mqls[1].matches ){
console.log('LG')
}
else if( !mqls[0].matches && !mqls[1].matches ){
console.log('SM')
}
}
for ( let i =0; i < mqls.length; i++ ){
test(mqls[i]);
mqls[i].addListener(test);
}
最佳答案
function checkScreen(){
const checkMobile = window.matchMedia('screen and (max-width: 575px)');
const checkTablet = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');
const checkDesktop = window.matchMedia('screen and (min-width: 992px)');
checkMobile.addListener(function(e){
if(e.matches) {
console.log('MOBILE');
}
});
checkTablet.addListener(function(e){
if(e.matches) {
console.log('TABLET');
}
});
checkDesktop.addListener(function(e){
if(e.matches) {
console.log('DESKTOP');
}
});
}
checkScreen()
我明白了,但也许有更好的解决方案?
已编辑
使用上面的解决方案,当我的页面加载或刷新时,我的函数不会启动,所以我必须这样做
mobile();
function mobile(){
const mql = window.matchMedia('screen and (max-width: 575px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('Mobile');
}
}
}
tablet();
function tablet(){
const mql = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('tablet');
}
}
}
desktop();
function desktop(){
const mql = window.matchMedia('screen and (min-width: 992px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('desktop');
}
}
}
如果我将媒体查询放入数组中,并在每次刷新时使用循环,控制台中的输出与数组中的元素一样多
可能有一些我不明白的地方。
关于javascript - JavaScript 中的多媒体查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58599373/