【问题标题】:How do I change or turn off a css attribute using Javascript/Jquery? [closed]如何使用 Javascript/Jquery 更改或关闭 css 属性? [关闭]
【发布时间】:2021-01-02 22:21:01
【问题描述】:

我通常能够使用它的 ID 选择一个元素并对其进行操作或通过它的关联类进行操作,但我不能对当前元素执行此操作,因为它使用的标签优先于我的更改。是否有覆盖标签或关闭适用于我元素的标签的部分 CSS?

下面是我要编辑的 CSS 元素

下面是我正在尝试编辑的 HTML 'div',实际项目以蓝色突出显示

【问题讨论】:

  • 这取决于您在检查器中看到的 style 属性是来自标记还是由于某些 JS... 当然,您的 CSS 中没有 width 。 . 使您的问题不清楚。
  • 您需要提供minimal reproducible example。我们看不到您尝试更改 CSS 的方式。

标签: javascript jquery css tags overriding


【解决方案1】:

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

当在样式声明中使用重要规则时,此声明会覆盖任何其他声明。

这在视觉上显示如下:

div {
  color: #ffffff00;
  padding: 30px;
  width: 50%;
  border-radius: 10px;
}

.first {
  background-color: blue !important;
}


/* Even though these styles are declared after .first, 
  .first takes precedence because it uses the !important rule*/

.second {
  background-color: red;
}
<!-- Both classes are applied to this div: -->
<div class="first second"></div>

因此,为了让您的规则具有更高的优先级,您也必须使用 !important 规则。 然而:

然而,使用 !important 是不好的做法,应该避免

所以请确保永远不要使用 !important,除非它是唯一的选择。

以下代码应作为您问题的基础:

let div = document.getElementById("example")
div.style.setProperty("background-color", "green", "important");
div {
  color: #ffffff00;
  padding: 30px;
  width: 50%;
  border-radius: 10px;
}

.first {
  background-color: blue !important;
}


/* Even though these styles are declared after .first, 
      .first takes precedence because it uses the !important rule*/

.second {
  background-color: red;
}
&lt;div id="example" class="first second"&gt;&lt;/div&gt;

希望对您有所帮助,祝您有美好的一天!

【讨论】:

  • 这对我来说非常有效。我能够使用以下内容: document.getElementById('ext-gen91').style.setProperty("font-size", "12px", "important")
【解决方案2】:

使用普通的 JS 你可以做到,这肯定有效,但是很hacky。

let yourLabel = document.getElementById("yourID");
yourLabel.setAttribute ('style', 'font-size: 11px !important;');

这将覆盖“重要!”属性,是纯香草JS。

let yourLabel = document.getElementById("yourID");
yourLabel.setAttribute ('style', 'font-size: 11px !important;');
#yourID {
  
  font-size: 166px !important;
  font-weight: 700 !important;
}
&lt;label id="yourID"&gt;label&lt;/label&gt; not label

运行 sn-p,现在可以正常工作了:_)

【讨论】:

  • 当我测试它时不起作用:jsbin.com/pezopoyuwi/1/edit?html,css,js,output
  • 我同意这不起作用。它做了一些事情,但不是我想要的,即关闭或重置 font-size 属性。
  • 奇怪的在 codepen 为我工作,将立即更新答案
  • @ptts 感谢您对代码进行修改。这将适用于现在。非常感谢您的帮助。
猜你喜欢
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多