[英]How can I reliably set the class attr w/JavaScript on IE, FF, Chrome, etc.?
I am using the below JS code in order to change the class when a link is clicked. 我使用下面的JS代码,以便在单击链接时更改类。
document.getElementById("gifts").setAttribute("class", "gkvSprite selected");
This is not working in IE but it does in FF and Chrome. 这在IE中不起作用,但它在FF和Chrome中起作用。 Then I changed the code to:
然后我将代码更改为:
document.getElementById("gifts").setAttribute("className", "gkvSprite selected");
Then it worked in IE, but stopped working in FF and Chrome. 然后它在IE中工作,但在FF和Chrome中停止工作。
Could someone please help me out here? 有人可以帮帮我吗?
You can reliably use the className
property instead of setAttribute
: 您可以可靠地使用
className
属性而不是setAttribute
:
document.getElementById("gifts").className = "gkvSprite selected";
More generally, there are a couple of attribute names that different browsers treat differently in setAttribute
: class
vs className
, and for
vs. htmlFor
. 更一般地,有一对夫妇的属性名称,不同的浏览器在区别对待
setAttribute
: class
VS className
,并for
与htmlFor
。 Libraries like Prototype , jQuery , and the like will smooth out these differences for you, although (again) in the specific situation of class
, you can reliably use the property instead. 像Prototype , jQuery等这样的库可以为你平滑这些差异,尽管(再次)在
class
的特定情况下,你可以可靠地使用属性。
You can go about this in a few ways. 你可以通过几种方式解决这个问题。
If you want to use setAttribute
you can detect which browser the client is using and then use class
in IE and classname
in Firefox. 如果要使用
setAttribute
,可以检测客户端使用的浏览器,然后在IE中使用class
,在Firefox中使用classname
。
The above would work but I would prefer using a div and assigning a new class for that. 上面会工作,但我更喜欢使用div并为此分配一个新类。
somediv.className='gkvSprite selected'
Or as TJ Crowder said above. 或者正如TJ克劳德上面所说。 Asign via
Classname
directily. 通过
Classname
直接签名。
If #gifts has a timed CSS3 transition set on it in CSS, setAttribute (and removeAttribute, and other js commands) also fails in some browsers. 如果#gifts在CSS中设置了定时的CSS3转换,则setAttribute(和removeAttribute以及其他js命令)在某些浏览器中也会失败。 The javascript must be delayed until the transition is done before it can modify it.
必须延迟javascript,直到转换完成才能修改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.