简体   繁体   English

我可以使用JavaScript获取媒体查询使用的维度吗?

[英]Can I use JavaScript to get the dimensions that media queries use?

For example here is a fiddle which shows how to change a font when the width drops below 200px. 例如,这是一个小提琴 ,它显示了当宽度降至200px以下时如何更改字体。

@media (max-width: 200px) {
  .test {
    font-size:40px;
  }
}

If you move the html window to the right to make it smaller you will see the point at which it hits 200px bc the font will change. 如果将html窗口向右移动使其更小,则会看到它达到200px bc的位置,字体将发生变化。

If someone could add a dynamic div to the fiddle so that this value would be output to the window this would be a cool test script for media queries. 如果有人可以将动态div添加到小提琴中,以便将该值输出到窗口,那么这将是媒体查询的不错的测试脚本。

Also, if there is a good reference on the web for the JavaScript interface to media queries. 另外,如果Web上有关于媒体查询的JavaScript接口的良好参考。 I hope there is one. 我希望有一个。 I have not found it yet. 我还没有找到。

You can add an event listener to window.matchMedia 您可以将事件监听器添加到window.matchMedia

if (matchMedia) {
    var mq = window.matchMedia("(max-width: 200px)");
    mq.addListener(WidthChange);
    WidthChange(mq);
}

// media query change
function WidthChange(mq) {

    if (mq.matches) {
        console.log('matches')
    }

}

Demo 演示版

I did using jQuery, hope this helps. 我确实使用过jQuery,希望对您有所帮助。

$( window ).resize(function() {
if($(window).width()<=200){
    $(".test").css("font-size","40px");
}
else{
    $(".test").css("font-size","20px");
} });

http://jsfiddle.net/7gup43rx/2/ http://jsfiddle.net/7gup43rx/2/

Here is what you were actually asking for. 这是您实际要的。 The snippet below will output the dimensions that media query uses. 以下代码段将输出媒体查询使用的尺寸。

http://jsfiddle.net/jbnt7nh1/8/ http://jsfiddle.net/jbnt7nh1/8/

// some code - updated fiddle

Here is a good point to start reading about the different widths in CSS. 这是开始阅读CSS不同宽度的好方法。

https://www.google.com/#q=quirksmode+screen+width https://www.google.com/#q=quirksmode+screen+width

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM