首页 > 解决方案 > 如何在桌面模式下禁用 CSS 媒体查询

问题描述

我的桌面 CSS 在您调整窗口大小时已经响应,并且我添加了媒体查询来处理移动设备,但是现在当我调整桌面窗口大小时,它使用了我不想要的移动媒体查询。

编码:

我将此添加到我的 html 文件中:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

我的 .css 文件中的媒体查询,当我处于桌面模式并且我正在调整窗口大小时,我想停用它:

@media only screen and (max-width: 415px) {
//code
}

在我调整大小时,它使用这个媒体查询。

我也有这个 Javascript 方法,如果不是在桌面模式下,我也只想获取宽度:

var width = screen.width;

我只想在移动设备上使用宽度,因为我的桌面网站已经响应并且可以工作。

先感谢您。

标签: javascripthtmlcss

解决方案


如果您希望此媒体查询仅在移动设备中可用,我将使用 JS 来识别设备并加载 css 查询文件。例如,像这样:

const ifIsMobile = { // detect the mobile devices
Android: function() {
    return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
    return (ifIsMobile.Android() || ifIsMobile.BlackBerry() || ifIsMobile.iOS() || ifIsMobile.Opera() || ifIsMobile.Windows());
}};




const loadMobileCss = () => { // add the link tag to load mobilestyles.css
                const linke = document.createElement("link");
                linke.rel = "stylesheet";
                linke.href = "mobilestyles.css";
                document.getElementsByTagName("head")[0].appendChild(linke);
            }


 if (ifIsMobile.any()) loadMobileCss(); //  if the device is mobile, load mobilestyles.css with the function loadMobileCss()

您必须将此代码放在您的网络头部才能使其工作。


推荐阅读