使用JavaScript创建CSS样式属性 [英] Create CSS styling properties using JavaScript
问题描述
像每个人都知道,我们可以使用像下面的CSS样式元素
Like everyone knows we can style an element using CSS like below
#a {
background-color : green;
}
并使用JS
document.getElementById('a').style.backgroundColor = "green";
但我想创建一些属性,例如 background-color
并且可以在CSS中使用。例如,我将创建一个属性,如foobar,然后我应该能够使用它如下
But I would like to create some property like background-color
and that can be used inside CSS. For example I will create a property like "foobar" then I should be able to use it like below
#a {
foobar : value;
}
这是可能吗?我想对包含这个属性的元素执行一些JS。
Is this possible? I would like to execute some JS on the element that includes this property.
在被称为重复的问题中的答案是如何创建新的CSS并将其添加到使用现有CSS属性的样式表。但是这里我试图创建自己的css属性...
Answers in the question referred to as a duplicate were how to create new CSS and add it to the style sheets using existing CSS properties. But here I am trying to create my own css property...
推荐答案
对包含此属性的元素执行一些JS。
I would like to execute some JS on the element that includes this property.
虽然你 style
object:
Although you could just write random properties to the style
object:
myElement.style.foobar = "value";
...和似乎在Chrome,Firefox,IE11甚至IE8上都可以存活,我会强烈建议不要这样做。
...and that seems to survive on Chrome, Firefox, IE11, even IE8, I would strongly recommend against it.
你可以更好地使用类或 data - *
属性。
You'd be much better off using a class or a data-*
attribute instead. You can query for them, for one thing.
如果你想创建自己的CSS(你在评论中说的话),我会认为<$
If you're trying to create your own CSS (something you said in a comment), I would think a data-*
attribute would be a good choice.
使用类:
var myElement = document.createElement('a');
myElement.className = "foobar";
// ...add it somewhere...
// Later
var myElements = document.querySelectorAll(".foobar");
// ...do something with the list...
code> data - * 属性:
or with a data-*
attribute:
var myElement = document.createElement('a');
myElement.setAttribute("data-foobar", "value");
// ...add it somewhere...
// Later
var myElements = document.querySelectorAll('[data-foobar="value"]');
// ...do something with the list...
querySelectorAll
支持所有现代浏览器和IE8。
querySelectorAll
is supported on all modern browsers, and also IE8.
这篇关于使用JavaScript创建CSS样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!