setAttribute各个浏览器都支持,但在IE7如下版本中,有些属性值仍是有差别的,好比javascript
obj.setAttribute("class","classname")
在ie8等主流浏览器能起效,但在IE7如下版本中不起做用,由于IE7如下版本不认得“class”,他们只认得“className”;css
单一的兼容性能够这样写html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .test{ width: 100px; height: 100px; background: blue; } .turn{ background: red; width: 200px; height: 300px; } </style> <script> window.onload = function() { document.getElementsByTagName('button')[0].onclick = function() { var div = document.getElementsByTagName('div')[0] if(div.getAttribute("class")){//判断是否存在 div.setAttribute("class","turn");/*IE8,chrome*/ }else{ div.setAttribute("className","turn")/*IE7-5*/ } } } </script> </head> <body> <button>点击切换class</button> <div class="test"></div> </body> </html>
以上代码能够让setAttribute的class兼容全部主流浏览器java
但除了class有差别外,还有下列属性也有差别chrome
为了解决上述问题就要写一个通用的跨浏览器的设置元素属性的接口方法:浏览器
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <style type="text/css"> .textcolor{ font-size:18px; color:red; } </style> <script type="text/javascript"> dom=(function(){ var fixAttr={ tabindex:'tabIndex', readonly:'readOnly', 'for':'htmlFor', 'class':'className', maxlength:'maxLength', cellspacing:'cellSpacing', cellpadding:'cellPadding', rowspan:'rowSpan', colspan:'colSpan', usemap:'useMap', frameborder:'frameBorder', contenteditable:'contentEditable' }, div=document.createElement('div'); div.setAttribute('class','t'); var supportSetAttr = div.className === 't'; return { setAttr:function(el, name, val){ el.setAttribute(supportSetAttr ? name : (fixAttr[name] || name), val); }, getAttr:function(el, name){ return el.getAttribute(supportSetAttr ? name : (fixAttr[name] || name)); } } })(); window.onload=function(){ var mydiv=document.getElementById("mydiv"); dom.setAttr(mydiv, 'class', 'textcolor'); } </script> </head> <body> </body> </html>
另外,一样能够使用element.style的方式去更改dom
例如spa
document.getElementById("testbt").className = "bordercss";
document.getElementById("testbt").style.cssText = "color: #00f;";
参考自:http://www.jb51.net/article/69685.htm.net