可以覆盖所有媒体查询吗? [英] Can all media queries be overriden?

查看:27
本文介绍了可以覆盖所有媒体查询吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个响应式网站,其中包含媒体查询以定位不同的移动设备,但希望在较小的设备上提供覆盖所有"链接.单击该链接时,该链接将删除所有媒体查询样式并将页面重置为默认样式,以 1024 像素宽显示站点.有没有办法做到这一点?

I have built a responsive website with media queries to target different mobile devices but would like to have an "override all" link available on smaller devices. When clicked, the link would remove all media query styles and reset the page to default styles, exposing the site as it would at 1024px wide. Is there a way to achieve this?

推荐答案

您可以做到这一点的唯一方法是使用 Javascript.我想出了两个解决方案:

元素上的 id/class:
将 id 或类应用于 html 元素:<html class="media-queries">.
在您的媒体查询中,每个选择器都以 .media-queries 开头:
CSS

The only way you can do this is with Javascript. I came up with two solutions:

id/class on <html> element:
Apply an id or class to the html element: <html class="media-queries">.
In your media-queries, every selector will start with .media-queries:
CSS

@media (max-width: 300px) {
    .media-queries #nav li {
        display: block;
    }
    .media-queries #main, .media-queries #aside {
        float: none;
    }
}

然后,您让 JS 删除 class="media-queries".
HTML

Then, you get JS to remove class="media-queries".
HTML

<a id="del-mq" href="#">Default style</a>

JavaScript

var delMQ = document.getElementById('del-mq');
delMQ.onclick = function() {
    document.getElementsByTagName('html')[0].removeAttribute('class');
}

jQuery

$('#del-mq').click(function() {
    $('.media-queries').removeClass();
});


优点:没有额外的 http 请求.
缺点:很多 css 选择器(.media-queries),如果使用 Sass 应该不会有问题:


Pros: no extra http requests.
Cons: lots of css selectors(.media-queries), which shouldn't be a problem if using Sass:

@media (max-width: 300px) {
    .media-queries {
        #nav...
        #main...
    }
}



外部媒体查询.css
所有媒体查询都放在一个单独的 css 文件中.用 包含它.
然后您获得 的 ID 并删除该元素.
HTML



External media-queries.css
All the media queries go in a separate css file. Include it with <link rel="stylesheet" href="media-queries.css">.
Then you get an ID for the <link> and remove the element.
HTML

<head>
    <link rel="stylesheet" href="default.css">
    <link id="media-queries" rel="stylesheet" href="media-queries.css">
</head>
<body>
    ...
    <a id="del-mq" href="#">Default style</a>
    ...
</body>

Javascript

var delMQ = document.getElementById('del-mq');
delMQ.onclick = function() {
    document.getElementsByTagName('head')[0].removeChild(document.getElementById('media-queries'));
}

jQuery

$('#del-mq').click(function() {
    $('#media-queries').remove();
});



优点:不需要大量的 css 选择器.
缺点:额外的 http 请求.



Pros: no need for lots of css selectors.
Cons: extra http request.

这篇关于可以覆盖所有媒体查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆