setAttribute各个浏览器都支持,但在IE7以下版本中,有些属性值还是有差异的,比如
obj.setAttribute("class","classname")
在ie8等主流浏览器能起效,但在IE7以下版本中不起作用,因为IE7以下版本不认得“class”,他们只认得“className”;
单一的兼容性可以这样写
<!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兼容所有主流浏览器
但除了class有差异外,还有下列属性也有差异
- class
- for
- cellspacing
- cellpadding
- tabindex
- readonly
- maxlength
- rowspan
- colspan
- usemap
- frameborder
- contenteditable
- style
为了解决上述问题就要写一个通用的跨浏览器的设置元素属性的接口方法:
<!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的方式去更改
例如
document.getElementById("testbt").className = "bordercss";
document.getElementById("testbt").style.cssText = "color: #00f;";
参考自:http://www.jb51.net/article/69685.htm