将CSS样式转换成JS变量?
16lz
2021-01-22
I'm trying to create vars for some styles that i want to and reuse, but can't seem to get it to work. What am I doing wrong?
我正在尝试为一些我想要的样式创建vars并进行重用,但似乎无法使其工作。我做错了什么?
var bgColor = "'background' : 'rgb(102,204,0)'";
var textColor = "'color' : 'rgb(40,40,40)'";
$('.className').css({bgColor, textColor});
4 个解决方案
#1
3
Taking a look at the documents on jquery css if you wanted to apply these values in a single call you'd need to create valid json. Per the documents:
如果您想在单个调用中应用这些值,那么就需要创建有效的json。每个文件:
var validValues =
{
"background-color": "#ffe",
"border-left": "5px solid #ccc"
};
or
或
var validValues =
{
backgroundColor: "#ffe",
borderLeft: "5px solid #ccc"
}
then
然后
$(selector).css(validValues);
Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name
注意,使用DOM表示法时,属性名周围的引号是可选的,但是使用CSS表示法时,由于名称中的连字符,它们是必需的
specifically the reason yours does not work is the following does not create valid json for jquery:
具体来说,您的失败原因是以下原因没有为jquery创建有效的json:
var bgColor = "'background' : 'rgb(102,204,0)'";
var textColor = "'color' : 'rgb(40,40,40)'";
var json = {bgColor, textColor};
json =
json =
{
bgColor: "'background' : 'rgb(102,204,0)'",
textColor: "'color' : 'rgb(40,40,40)'"
}
更多相关文章
- 如何在动态创建的HTML标签内容中避免单引号?
- php单引号和双引号的区别
- 单引号,双引号,javascript,HTML,转义字符
- 不使用PHP框架的原因?
- 如何调试UPDATE函数在PHP中无法正常工作的原因?
- 关于uoloadify不能显示效果原因(thinkphp5仿百度糯米)
- fgetcsv()错误地将双引号添加到第一行的第一个元素
- 这是什么原因啊,没有找出错来啊(数据库用的是mysql)
- 使用IP地址方法登录MySQL数据库Can't connect to MySQL serv