使用JavaScript检测动态媒体查询,而无需在脚本中硬编码断点宽度? [英] Detect dynamic media queries with JavaScript without hardcoding the breakpoint widths in the script?

查看:66
本文介绍了使用JavaScript检测动态媒体查询,而无需在脚本中硬编码断点宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种轻量级,灵活,跨浏览器的解决方案,以访问JavaScript中的CSS媒体查询, 而在JavaScript代码中不重复CSS断点

I've been searching for a lightweight, flexible, cross-browser solution for accessing CSS Media Queries in JavaScript, without the CSS breakpoints being repeated in the JavaScript code.

CSS技巧发布了 CSS3基于动画的解决方案,似乎很不错,但是建议使用 Enquire.js .

CSS-tricks posted a CSS3 animations-based solution, which seemed to nail it, however it recommends using Enquire.js instead.

Enquire.js似乎仍然需要在脚本中对Media Query大小进行硬编码,例如

Enquire.js seems to still require the Media Query sizes to be hardcoded in the script, e.g.

enquire.register("screen and (max-width:45em)", { // do stuff }

问题

到目前为止,所有用于访问Java媒体查询的解决方案似乎都依赖于在脚本中硬编码的断点.

All solutions so far for accessing Media Queries in Javascript seem to rely on the breakpoint being hardcoded in the script. How can a breakpoint be accessed in a way that allows it to be defined only in CSS, without relying on .on('resize')?

尝试的解决方案

我已经制作了自己的版本,该版本可在IE9 +中使用,它使用了一个隐藏元素,该元素使用:content 属性添加了查询触发时想要的任何内容(与 ZeroSixThree的解决方案):

I've made my own version that works in IE9+, using a hidden element that uses the :content property to add whatever I want when a Query fires (same starting point as ZeroSixThree's solution):

HTML

<body>
    <p>Page content</p>
    <span id="mobile-test"></span>
</body>

CSS

#mobile-test {
    display:none;
    content: 'mq-small';
}
@media screen only and (min-width: 25em) {
    #mobile-test {
        content: 'mq-medium';
    }
}
@media screen only and (min-width: 40em) {
    #mobile-test {
        content: 'mq-large';
    }
}

使用jQuery的JavaScript

// Allow resizing to be assessed only after a delay, to avoid constant firing on resize. 
var resize;
window.onresize = function() {
    clearTimeout(resize);
    // Call 'onResize' function after a set delay
    resize = setTimeout(detectMediaQuery, 100);
};

// Collect the value of the 'content' property as a string, stripping the quotation marks
function detectMediaQuery() {
    return $('#mobile-test').css('content').replace(/"/g, '');
}

// Finally, use the function to detect the current media query, irrespective of it's breakpoint value
$(window).on('resize load', function() {
    if (detectMediaQuery() === 'mq-small') {
        // Do stuff for small screens etc
    }
});

这样,媒体查询的断点完全由CSS处理.如果您更改断点,则无需更新脚本.该怎么办?

This way, the Media Query's breakpoint is handled entirely with CSS. No need to update the script if you change your breakpoints. How can this be done?

推荐答案

尝试一下

const mq = window.matchMedia( "(min-width: 500px)" );

matchs属性根据查询结果返回true或false,例如

The matches property returns true or false depending on the query result, e.g.

if (mq.matches) {

  // window width is at least 500px
} else {
  // window width is less than 500px
}

您还可以添加一个事件侦听器,该侦听器在检测到更改时将触发:

You can also add an event listener which fires when a change is detected:

// media query event handler
if (matchMedia) {
  const mq = window.matchMedia("(min-width: 500px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

// media query change
function WidthChange(mq) {
  if (mq.matches) {
    // window width is at least 500px
  } else {
    // window width is less than 500px
  }

}

这篇关于使用JavaScript检测动态媒体查询,而无需在脚本中硬编码断点宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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