【问题标题】:jQuery: Check if window is smaller than x units other than pixels (e.g. em, rem)?jQuery:检查窗口是否小于像素以外的 x 单位(例如 em、rem)?
【发布时间】:2018-08-28 00:50:06
【问题描述】:

听起来微不足道,但我该如何检查呢?我在 SASS 中有以下断点:

$width_breakpoints: (
        small: 39.9375em,
        medium: 40em,
        large: 76em
);

现在我想检查以下(伪代码):

if($(window).width() < 39.9375em) {
    // add current-mode-mobile class to a certain element
}

如何实际检查宽度是否小于 X em 或 X rem 或 X percent?

【问题讨论】:

  • 39.9375em 像素需要什么?
  • em 取决于parent 元素的font-sizerem 取决于body 的字体大小。只需获取您需要的字体大小并在 javascript/jquery 条件下使用它

标签: javascript jquery css sass media-queries


【解决方案1】:

对于 IE10+:

if (window.matchMedia("(min-width: 39.9375em)").matches) {
  /* the viewport is at least 39.9375 em wide */
} else {
  /* the viewport is less than 39.9375 em wide */
}

【讨论】:

  • IE caniuse.com/#feat=matchmedia。
  • 我不知道这个 matchMedia,它看起来很不错。
  • 像魅力一样工作。
【解决方案2】:

这是一个甚至不需要 jQuery 的解决方案。

var widthInEm =  window.innerWidth /
          parseFloat(getComputedStyle(document.querySelector('body'))['font-size'])

if(widthInEm < 39.9375) {
   // add current-mode-mobile class to a certain element
}

【讨论】:

  • 因此以像素为单位的宽度必须转换为所需的单位,反之亦然?听起来像是一个可以接受的想法,我会检查并提供反馈。
猜你喜欢
  • 1970-01-01
  • 2012-08-27
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
  • 2011-05-27
  • 1970-01-01
相关资源
最近更新 更多