我有一个 div:
<div class="badger-left"></div>
这个 CSS:
/* Change style dynamically according to the bg-color attribute added to the div from jQuery */
.badger-change:after {
background-color: attr(bg-color);
}
这个 jQuery 添加一个属性和一个类:
$('.badger-left').addClass('badger-change').attr('bg-color','red');
由于 jQuery 不能像 CSS 那样执行 :after
,所以我想到了这种方法,但它失败了。我应该尝试什么?
谢谢
编辑:颜色会从 jQuery 动态改变,它不会总是红色。
最佳答案
因此,您不能将它传递给颜色值,因为它将被解释为字符串而不是引用。你可以传入content
值来证明这一点。请注意,您需要为 :after
提供一些布局,包括内容或显示或尺寸。
这是一个 hacky 解决方法。我个人会重构它以不使用伪样式,但这将适用于您当前的实现:
function addStyle(color) {
$('<style>.badger-left:after { background-color: ' + color + ';</style>').appendTo('head');
}
// example addStyle('red');
关于javascript - 使用 jQuery 动态更改 CSS 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162621/