gpt4 book ai didi

javascript - @media 查询被 javascript DOM 操作覆盖

转载 作者:行者123 更新时间:2023-11-30 16:32:54 26 4
gpt4 key购买 nike

我有一个@media 查询通过设置“display:none;”来隐藏/显示 DOM 元素基于屏幕方向。以下 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);

元素不再根据方向隐藏/显示

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

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

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

最佳答案

带有 jQ​​uery 的动画/CSS 通常用相应的样式修改 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。内联样式具有最高优先级(唯一异常(exception)是使用 important)另请注意媒体查询 doesn't have any extra precedence,它们的工作方式与 IF 语句一样。

与此同时,您可以使用您已经完成的 [important][1] 覆盖内联样式:

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

显然,没有其他方法可以从样式表中覆盖内联 CSS。如果您考虑一下,没有比直接在 DOM 节点本身的样式<中编写 CSS特定的 DOM 节点引用了 属性。

在您的场景中,您可以在执行 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.

关于javascript - @media 查询被 javascript DOM 操作覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33082118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com