How can I reliably set the class attr w/JavaScript on IE, FF, Chrome, etc.?

独自空忆成欢 提交于 2019-11-28 03:11:30

问题


I am using the below JS code in order to change the class when a link is clicked.

document.getElementById("gifts").setAttribute("class", "gkvSprite selected");

This is not working in IE but it does in FF and 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.

Could someone please help me out here?


回答1:


You can reliably use the className property instead of 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. 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.




回答2:


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.

The above would work but I would prefer using a div and assigning a new class for that.

somediv.className='gkvSprite selected'

Or as T.J. Crowder said above. Asign via Classname directily.




回答3:


If #gifts has a timed CSS3 transition set on it in CSS, setAttribute (and removeAttribute, and other js commands) also fails in some browsers. The javascript must be delayed until the transition is done before it can modify it.



来源:https://stackoverflow.com/questions/2490627/how-can-i-reliably-set-the-class-attr-w-javascript-on-ie-ff-chrome-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!