最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Trigger a media query with javascript - Stack Overflow

programmeradmin3浏览0评论

Is it possible to trigger the media query @media (max-width: 600px) { .a { ... } } when clicking on a button with Javascript ? (without having the browser width really < 600px)

// $('#b').click(function(){ // trigger the media query });
.a { background-color: green; }

@media (max-width: 600px) { 
    .a { background-color: yellow; /* many other rules */ }
}
<script src=".11.1/jquery.min.js"></script>
<div class="a">Hello</div>
<input id="b" type="button" value="Change" />

Is it possible to trigger the media query @media (max-width: 600px) { .a { ... } } when clicking on a button with Javascript ? (without having the browser width really < 600px)

// $('#b').click(function(){ // trigger the media query });
.a { background-color: green; }

@media (max-width: 600px) { 
    .a { background-color: yellow; /* many other rules */ }
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a">Hello</div>
<input id="b" type="button" value="Change" />

Share Improve this question asked May 29, 2016 at 19:06 BasjBasj 46.7k110 gold badges458 silver badges808 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You cannot trigger media query styles with JavaScript, but you can enable them by using a separate stylesheet and modifying its media attribute. Here is what I mean:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" media="all" href="regular_styles.css">
    <link rel="stylesheet" media="(max-width: 600px)" href="small_screen.css" id="small">
</head>
<body>

    <div class="a">Hello</div>
    <input id="b" type="button" value="Change" />

    <script src="jquery.min.js"></script>
    <script>
        $('#b').click(function(){
            // set the media query perimeter to "all"
            $('#small').attr('media', 'all');
        });
    </script>
</body>
</html>

regular_styles.css

.a { background-color: green; }

small_screen.css

.a { background-color: yellow; /* many other rules */ }
发布评论

评论列表(0)

  1. 暂无评论