javascript - 如何将 CSS 媒体查询的结果传递给 JS?

标签 javascript html css leaflet

我有一个 JS 变量控制页面的样式。我希望它根据屏幕分辨率而改变。我怎样才能让它依赖于 CSS 媒体查询的结果。

我知道我可以直接在 JS 中检查屏幕分辨率,但我想将所有样式决定保留在 CSS 中,而不是将其分散到 JS 和 CSS 文件中。

为了避免 XY 问题:我正在使用 Leaflet 和 JS 变量决定列出可用图层的 map 控制面板是否折叠。它应该在小屏幕(移动设备)上折叠,而不是在大屏幕(适当的显示器)上折叠。

相关代码如下

html,
body {
  height: 100%;
  margin: 0;
}

#map {
  width: 600px;
  height: 400px;
}

@media (min-width: 1000px) {
  #map {
    width: 1000px;
    height: 900px;
  }
}
<!DOCTYPE html>
<html>
<!--based on https://leafletjs.com/examples/layers-control/ example -->

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>
  <link rel="stylesheet" href="example.css" />
</head>

<body>
  <div id='map'></div>
  <script>
    var positron = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
        attribution: '#{openstreetmap_copyright_notice}, basemap: &copy; <a href=\"http://cartodb.com/attributions\">CartoDB</a>',
        subdomains: 'abcd',
        maxZoom: 19
      }),
      osmcarto = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      });

    var map = L.map('map', {
      center: [39.73, -104.99],
      zoom: 10,
      layers: [positron]
    });

    var baseLayers = {
      "positron": positron,
      "osm-carto": osmcarto
    };

    L.control.layers(baseLayers, {}, {
      collapsed: false
    }).addTo(map); //false/true should be specified by CSS
  </script>
</body>

</html>

最佳答案

非常俗气的解决方案,但这意味着不要在 JS 中硬编码任何宽度属性。

向页面添加一个虚拟的、不可见的元素。

<div id="dummy"></div>

#dummy::after {
  display: none;
  content: 'false';
}

@media (min-width: 1000px) {
  #dummy::after {
    content: 'true';
  }
}

然后读取JS中content的值:

var isBigScreen = window.getComputedStyle(
    document.querySelector('#dummy'), ':after'
).getPropertyValue('content');

isBigScreen 将为 "true""false"。如果屏幕尺寸发生变化,您可能需要添加一些代码来重新检查。

if(isCollapsed === '"false"') {
    isCollapsed = false;
} else {
    isCollapsed = true;
}

可用于将其转换为标准 bool 值。

关于javascript - 如何将 CSS 媒体查询的结果传递给 JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51752884/

相关文章:

javascript - WordPress JavaScript 类型错误 : Cannot read property 'text' of null

javascript - 纯 CSS 旋转器卡住

javascript - VS 2013 查找并替换 document.getElementById ("elementId").value 为 $("#elementId).val()

php - 如何将php表格放入html侧边栏?

html - 隐藏/显示 div 是响应式设计的最佳实践吗?

javascript - 无法标记通过javascript动态选中的复选框

javascript - React Material onClick Collapse [答案已更新]

javascript - 停用 Bootstrap 事件标签单击

适用于 IE7 和 IE8 的 HTML5 和 CSS3

css - AJAX 加载指示器作为动画 PNG Sprite 的最佳实践/工具?