javascript - 在不影响 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 的新属性
解决方案
您可以在进行更改之前获取元素的计算样式:
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>
推荐阅读
- python - TensorBoard 不会更新 TensorFlow Slim 的标量
- xml - Perl:XML Twig 插入数据
- database - 第一次运行 docker-compose up 时运行迁移或加载模式的最佳方法是什么?
- haproxy - 如何防止 502 状态代码作为 haproxy 作为负载均衡器的响应
- python-3.x - 如何使用单个滑块创建具有可滚动 x 轴的多个绘图
- javascript - 从选中的复选框中获取文本
- sql - 选择计数明智的记录直到限制
- spring - Spring 4 HttpSession 对于每个控制器方法都不同
- r - 将数据框中的所有字符串更改为几个不同的值 r 之一(不重复)
- c# - 在泛型类中转换数据错误