首页 > 解决方案 > 如何通过 JavaScript 获取媒体查询定义的当前 CSS 值?

问题描述

我对这个问题的标题与现有问题几乎完全相同,但不幸的是,以下答案不适用:

如何在javascript中获取媒体查询定义的当前css值?

首先,我试图在使用特定类创建任何元素之前确定特定的 CSS 类值是什么。

其次,我想以百分比形式获取样式表中所述的值,而不是像使用getComputedStyle.

第三个复杂性(是的,好像我需要更多!)是该类是在特定 Angular 组件的样式表中定义的,而不是在全局样式表中。我找不到任何我在document.styleSheets.

最重要的是,即使我将类移动到全局样式表,并查看由列出CSSStyleRules的所有 s 的所有s ,虽然我可以找到该特定类的规则,但不幸的是,这些规则没有反映媒体查询动态进行的任何更改。CSSStyleSheetdocument.styleSheets

这是涉及的特定CSS:

.my-class {
  display: flex;
  line-height: 1;
  min-width: 0;
  padding-bottom: 1em;
  padding-right: 1em;
}

@media all and (min-width: 0) {
  .my-class {
    width: 94%;
  }
}

@media all and (min-width: 768px) {
  .my-class {
    width: 47%;
  }
}

@media all and (min-width: 1024px) {
  .my-class {
    width: 31.5%;
  }
}

@media all and (min-width: 1366px) {
  .my-class {
    width: 23.5%;
  }
}

@media all and (min-width: 1700px) {
  .my-class {
    width: 19%;
  }
}

当我resize从浏览器窗口收到一个事件时,我想要知道CSS 和媒体查询选择了多少宽度,以百分比表示。这样我就可以知道有多少使用我的类的项目可以水平显示,然后在计算中使用该值来确定应该从服务器获取多少项目的虚拟分页列表。

我很确定可以使用一种解决方案,但这并不理想:window.matchMedia

通过 JavaScript 监控媒体查询的问题在于 JavaScript 代码必须与 CSS 中的任何更改手动同步,并且 CSS 中的matchMedia每个断点都有一个单独的断点。

标签: javascriptcssangular

解决方案


我想到了两个选择

1(如你所述)

// reverse because you are looking for min width, If the min width is 1300 you know that all the values after it will be false (in the reversed arr)
const breakPointSizes = [0, 768, 1024, 1366, 1700].reverse()
const widths = [94, 47, 31, 23, 19].reverse() // You will have to match manually with what you have in css

const mediaMatches = breakPointSizes.map(size =>
  window.matchMedia(`(min-width: ${size}px)`)
)

window.addEventListener("resize", () => {
  const indexOf = mediaMatches.findIndex(mediaMatch => mediaMatch.matches)
  const width = widths[indexOf]
  console.log(width)
})

如果你想要一种动态的方式,那么我建议做的是在 dom 的某个地方隐藏该类的一个独特元素,然后根据当前值计算百分比

window.addEventListener('resize', () => {
  const contatinerWidth = document.getElementById('container').getBoundingClientRect().width;
  const elmWidth = document.getElementById('elm').getBoundingClientRect().width;
  const percentage = elmWidth / contatinerWidth;
  // At this point you know whats the percentage that should be given by your css class
  console.log(percentage)
})
#container {
 position: fixed;
 top: -300px; 
 /* So no one can see it **/
 width: 100vw;
}

.test {
 width: 50%;
}

  

@media only screen and (max-width: 600px) {
    .test {
        width: 70%;
    }
}
<div id="container">
 <div id="elm" class="test">
<div>


推荐阅读