jQuery:使用对象设置元素的“样式”属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2762775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Setting 'style' attribute of element with object
提问by JamesBrownIsDead
I saw this in our codebase the other day:
前几天我在我们的代码库中看到了这一点:
link.attr('style', map({
color: '#9a4d9e',
cursor: 'default'
}));
map
is defined as:
map
定义为:
function map(map) {
var cssValue = [];
for (var o in map) {
cssValue.push(o + ':' + map[o] + ';')
}
return cssValue.join(';');
}
Is map
necessarily? Is there a shorter way to do this?
是map
必然吗?有没有更短的方法来做到这一点?
It's important to note that the "style" attribute overrides any styles set by a class added/defined in the "class" attribute.
重要的是要注意,“style”属性会覆盖“class”属性中添加/定义的类设置的任何样式。
回答by Kobi
Probably not. A better solution may be to use CSS:
可能不是。更好的解决方案可能是使用 CSS:
link.css({color: '#9a4d9e',
cursor: 'default'});
However, .attr('style',)
also removes the previous inline style, so it doesn't behave exactly the same.
If you are going to use attr
, it's input should be a string, not an object, it isn't specialized to work with the style
attribute. an alternative in that case is:
但是,.attr('style',)
也删除了以前的内联样式,因此它的行为并不完全相同。
如果您要使用attr
,它的输入应该是一个字符串,而不是一个对象,它不是专门用于处理该style
属性的。在这种情况下,另一种选择是:
link.attr('style', "color:'#9a4d9e';cursor:'default'");
Seems cleaner in this case. In other cases, your map
makes it easier to insert variables into the CSS.map
could have been named better though. It also has an implementation error - it adds double semicolons between attributes: color:red;;cursor:default;
在这种情况下看起来更干净。在其他情况下,您map
可以更轻松地将变量插入 CSS。map
本来可以更好地命名。它还有一个实现错误——它在属性之间添加了双分号:color:red;;cursor:default;
A simple solution to remove the previews style is to call .removeAttr('style')
before calling css
.
删除预览样式的一个简单解决方案是.removeAttr('style')
在调用css
.
回答by AngelaG
.addClass('highlight') to element. Where your css class is predefined. (this worked for me as it didn't want to take 2 style attribute changes)
.addClass('highlight') 到元素。您的 css 类是预定义的。(这对我有用,因为它不想进行 2 个样式属性更改)