是否可以在JavaScript中使用CSS之类的媒体查询功能? [英] Is it possible to use css like media queries in javascript?

查看:77
本文介绍了是否可以在JavaScript中使用CSS之类的媒体查询功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以像在CSS中一样在 javascript 中使用媒体查询? 我想处理 device-width orientation 并触发一个函数.

I am wondering if there is a way to use media queries in javascript like i use it in CSS ? i want to handle device-width or orientation and fire a function .

现在我正在使用此代码:

now i am using this code :

window.onresize = function(event) {
    /* test for various sizes */
};

但这对我没有好处,我不知道如何使它工作.

but it is no good for me , i don't know how to make it work .

我需要它能在没有第三个奇偶校验库的情况下在最新的chrome中工作,我不确定是否可能.

i need it to work in latest chrome without third parity libraries , i'm not sure if it is possible .

推荐答案

我建议使用window.matchMedia方法,该方法可让您测试特定的媒体查询,并在匹配或不匹配时添加事件侦听器.

I would suggest using window.matchMedia method , wich allows you to test for a particular media query and add an event listener whenever it's matched or not .

示例:

var mq = window.matchMedia("(max-width: 600px)");
mq.addListener(function(event){
    if (event.matches) {
        console.log("Small Screen mode !");
    }
});

示例2:

onOrientationChange = function(event){
    if (event.matches) {
        console.log("Portrait mode!");
    }
};

var mq = window.matchMedia("(orientation: portrait)");
mq.addListener(onOrientationChange);

/* ... /*

/* When you no longer need to receive notifications , you can remove the listener */

mq.removeListener(onOrientationChange);

Chrome 9+,Firefox 6+,IE10 +中支持此API

This API is supported in : Chrome 9+ , Firefox 6+ , IE10+

有关 MDN

这篇关于是否可以在JavaScript中使用CSS之类的媒体查询功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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