【问题标题】:JavaScript media query vs CSS media queryJavaScript 媒体查询与 CSS 媒体查询
【发布时间】:2022-01-25 23:29:11
【问题描述】:

我注意到 JavaScript 媒体查询似乎在等效的 CSS 之后才生效。

我创建了两个示例来说明我在说什么:

第一个例子

HTML:

<div class="foo">
  bar
</div>

CSS:

.foo {
  background-color: orange;
}


@media(max-width: 300px) {
  .foo {
    background-color: blue;
    transform: translateY(100px);
    transition: all 300ms ease-out;
  }
}

jsbin链接为:here

当屏幕宽度从更大的东西变为 300 像素或更少时,就会发生过渡。

但是在创建响应式设计时,这种过渡可能会很烦人。我正试图摆脱它们。下面的 Javascript 和 CSS 解决了这个问题,但我不确定它是否可靠。

第二个例子

HTML

<div class="foo">
  bar
</div>
<button>toggle translateY to 200px</button>

CSS

.transition {
  transition: all 300ms ease-out;
}

.foo {
  background-color: orange;
}


@media(max-width: 300px) {
  .foo {
    background-color: blue;
    transform: translateY(100px);
  }
}

.translateY {
  transform: translateY(200px);
}

JavaScript:

const w = window.matchMedia("(max-width: 300px)");
const div = document.querySelector(".foo");
const button = document.querySelector('button');

function fun(e) {
  if (e.matches) {
     div.classList.add('transition');
  } else {
     div.classList.remove('transition');
  }
}

// for initial screen width change detection
fun(w);

w.addEventListener('change', fun);

button.onclick = function() {
  div.classList.toggle('translateY');
}

jsbin 链接是here

当屏幕宽度从更大的东西变为 300 像素或更少时,似乎会依次发生以下事情:

  1. CSS transform: translateY(100px) 在 Flash 中呈现。
  2. transition 类由 JavaScript 添加到 div

通过单击该按钮,它可以确保 transition 类正在工作。

此示例不会导致任何不必要的过渡,因为屏幕尺寸从更大的尺寸变为 300 像素或更小。

因此,似乎任何 CSS 媒体查询都在 JavaScript 等效媒体查询之前呈现。我认为这是一件好事。但我不确定,这是标准的良好支持行为吗?基于这种行为构建逻辑是否安全?

【问题讨论】:

  • 被覆盖不是因为 JSmedia 比 CSSmedia 多,而是因为 div.style 将元素中的样式作为属性。像这样:
    你总是可以在 CSS 中添加一些 !important
  • 我想试试let style = document.querySelector("style"); style.innerHTML = "@media(max-width: 300px) { .foo { background - color: blue; } } .foo { background - color: green; } ";

标签: javascript css media-queries


【解决方案1】:

这是CSS specificity的一部分

内联样式添加到元素(例如style="font-weight: bold;")总是覆盖外部样式表中的任何样式,因此可以被认为具有最高特异性

您发布的 javascript 代码将添加内联样式(通过元素的 style 属性),因此具有最高的特异性。 (它与 js 媒体查询无关,它只是与你如何将 JS 中的样式应用于元素有关


更新在有问题的 cmets/update 之后

同样,这取决于您何时加载 CSS 和 JS。如果您首先包含 CSS 文件,由于它是渲染阻塞资源,因此将首先应用它。

我不确定,为什么不通过 CSS 媒体查询应用所有规则?

const div = document.querySelector(".foo");
const button = document.querySelector('button');

button.onclick = function() {
  div.classList.toggle('translateY');
}
.foo {
  background-color: orange;
}

@media(max-width: 300px) {
  .foo {
    background-color: blue;
    transform: translateY(100px);
    transition: all 300ms ease-out;
  }
}

.translateY {
  transform: translateY(200px);
}
<div class="foo">
  bar
</div>
<button>toggle translateY to 200px</button>

【讨论】:

  • 您好,感谢您指出我的错误。我试图以最小的方式表达我的问题。我已经编辑了我的代码以正确反映我遇到的问题。
猜你喜欢
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 2021-08-23
  • 2012-02-15
  • 2014-04-10
  • 2019-12-09
  • 1970-01-01
相关资源
最近更新 更多