在不使用 getComputedStyle() 的情况下将 CSS 断点传递给 JS



我们正在努力减少可能由getComputedStyle()等因素引起的强制回流。

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

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

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

您是否有其他方法可以在没有强制重排的情况下将 CSS 断点传递给 JS?

谢谢!

将以下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。另请参阅对之前关于"如何通过javascript检查元素的可见性?"的回答。

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

如果您有多个断点,

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

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

下面是一个示例:

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

最新更新