首页 > 解决方案 > 在不影响 CSS 值的情况下更改元素的类名

问题描述

我有一个 DOM 元素,我只想更改元素的 className。我想保持 css 值不变。(对于外部 css 和内联 css)

例如,如果我有这个:

.sample{
  display: block
  font-size: 10px,
  font-color: #fff
}
<div class="sample">...</div>

在做了一些 JavaScript 操作之后,我需要达到这个:

.newCss{
  display: block
  font-size: 10px,
  font-color: #fff
}
<div class="newCss">...</div>

注意:对于 css 没有严格的规定,可以有 100 个值或只有 1 个值的 css 选择器。注意 2:没有 .newCss 之类的 css 选择器,我应该将 css 属性从 .sample 转换为一个名为 .newCss 的新属性

标签: javascripthtmljquerycssdom

解决方案


您可以在进行更改之前获取元素的计算样式:

const style = getComputedStyle(theElement);

然后将该样式直接应用于元素:

theElement.style.cssText = style.cssText;

然后删除类不会改变元素的样式,因为它是内联样式的。

例子:

const theElement = document.querySelector(".sample");
console.log("before:", theElement.className);
setTimeout(() => {
    const cssText = getComputedStyle(theElement).cssText;
    theElement.className = "newCss";
    theElement.style.cssText = cssText;
    console.log("after: ", theElement.className);
}, 800);
.sample{
  display: block;
  font-size: 10px;
  color: #fff;
  background-color: black;
}
.newCss {
  background-color: yellow;
}
<div class="sample">this is the div</div>

如果类在 CSS 中具有与之关联的样式,则可能会影响元素的样式。如果您需要防止这种情况,请先更改类,然后分配 CSS 文本:

例子:

const theElement = document.querySelector(".sample");
console.log("before:", theElement.className);
setTimeout(() => {
    theElement.style.cssText = getComputedStyle(theElement).cssText;
    theElement.className = "newCss";
    console.log("after: ", theElement.className);
}, 800);
.sample{
  display: block;
  font-size: 10px;
  color: #fff;
  background-color: black;
}
<div class="sample">this is the div</div>


推荐阅读