@media 查询被 javascript DOM 操作覆盖

@media query overwritten by javascript DOM manipulation

我有一个@media 查询 hiding/showing 一个 DOM 元素,方法是根据屏幕方向设置 "display:none;"。以下 CSS 工作正常。

@media all and (orientation: landscape) {
  #header-container {
    display: none; 
  }
}

但是在我的 javascript 中隐藏和显示相同的元素后,媒体查询似乎中断了。例如

//JS

this.element.find('#header-container').css(display: "none");

//And later..

this.element.find('#header-container').fadeIn(500);

元素不再 hidden/shown 基于方向

我的猜测是 .fadeIn() 方法为显示设置了一个新值 属性,我发现解决这个问题的唯一方法是将 !important 放在媒体查询中,如下所示:

@media all and (orientation: landscape) {
  #header-container {
    display: none !important; 
  }
}

即使在 DOM 操纵之后,使用 !important 是使媒体查询持久化的唯一方法吗?

您看到此行为的原因是 jQuery fadeIn 方法添加了内联 CSS,因此这将覆盖样式表中的内容。你可以有一些 JS 再次淡出/隐藏它。我不建议将 display: none !important 放在上面,因为那样你将无法使用 JS 来控制可见性。我假设在某些状态下您希望显示此元素。

以下任何一项都应该有效。

//JS

this.element.find('#header-container').css(display: "none");

//And later..

this.element.find('#header-container').fadeIn(500);

// Later again.

this.element.find('#header-container').fadeOut(500);
this.element.find('#header-container').hide();

如果你post更多代码我可以给你更详细的答案。

希望对您有所帮助。

您可以像这样将 javascript 包装在 if 语句中,但在响应式设计中效果不佳。只是另一种方法。

if (window.innerWidth > window.innerHeight){
    some javascript for landscape position
}
else{
    some javascript for portrait position
}

Animation/CSS 和 jQuery 通常用各自的样式修改 style 属性。因此,如果它在其中写入一些 display 属性 将覆盖样式表中的 CSS

<div id="header-container" style="display:block;opacity:1"></div>

@media all and (orientation: landscape) {
  #header-container {
    display: none; 
  }
}

应该是像上面这样的情况,所以display会变成block而不是none。内联样式具有最高的优先级(唯一的例外是使用 important). Also note that media-query doesn't have any extra precedence,它们就像 IF 语句一样工作。

与此同时,您可以使用 [important][1] 覆盖内联样式,您已经这样做了:

@media all and (orientation: landscape) {
  #header-container {
    display: none !important; 
  }
}

显然,没有 other 方法可以从样式表中覆盖内联 CSS。如果您考虑一下,对 DOM 节点的引用不能比直接在 DOM 节点上写 CSS 具体 本身在其 style 属性中。

在您的场景中,您可以在执行 jQuery 动画后重置元素的 style,因此在 fadeIn 完成后重置 style

this.element.find('#header-container').fadeIn(500, function(){
    $(this).attr('style', '');
});

To briefly list the different cases in precedence order:

  1. Style declared in "style attribute" with !important keyword.

  2. Style declared in "stylesheet" with !important attribute.

  3. Normal style declared in style attribute (without !important attribute).

  4. Normal Style in style sheet.

redneck 样式移除 :), 获取淡入效果,成功淡出 -> 移除样式(由淡入生成) 覆盖媒体查询。

this.element.find('#header-container').fadeIn(500, function() {
    $(this).removeAttr('style');
});