将CSS断点传递给JS而不使用getComputedStyle()

时间:2018-02-01 12:42:31

标签: javascript performance

我们正在尽量减少可能由getComputedStyle()等内容引起的强制回流。

我们的问题: 目前,我们通过使用具有以下样式的DOM元素将CSS断点传递给JavaScript:

.breakpoint {
  display: none;

  @media (min-width: $breakpoint-medium) {
    display: block;
  }

  @media (min-width: $breakpoint-large) {
    display: flex;
  }
}

然后在JS中,我们使用display检查getComputedStyle()属性,这会导致强制回流。

您是否有其他方法将CSS断点传递给JS而没有强制回流?

谢谢!

2 个答案:

答案 0 :(得分:0)

将以下div添加到您的html中:

<body>
   ... your html here
   <div id="breakpoint"></div>
</body>

并将其添加到您的SCSS:

#breakpoint{
   opacity: 0; //so you do not see it
   width: 1px; //so it works even with a 0 pixel canvas
   position: fixed; // so as not to change your page layout
      @media (max-width: $breakpoint-medium){
         display: none;
      }
   }
}

然后在javascript中执行以下操作:

var getCurrentBreakpoint = function(){
  return document.getElementById('breakpoint').offsetWidth > 0?'desktop':'tablet';
}
//getCurrentBreakpoint() = 'desktop' on desktop
//getCurrentBreakpoint() = 'tablet' on devices smaller than $breakpoint-medium

此答案之所以有效,是因为如果某个元素的offsetWidth在所有浏览器中都被隐藏,则返回0。另请参见answer,这是关于“如何通过javascript检查元素的可见性?”的先前问题的。

如果我有两个以上的断点怎么办?

如果您有多个断点,只需创建多个div,每个断点一个即可。然后确保每个断点div仅在一个断点范围内可见。

答案 1 :(得分:0)

您也可以使用insertRule()方法,使用JavaScript设置CSS断点。

这里是一个例子:

const css = window.document.styleSheets[0];
css.insertRule(`
  @media (min-width: 768px) {
    .breakpoint {
      display: none;
    }
  }
`, css.cssRules.length);