JS setAttribute兼容

问题和表现:

最近实践中遇到的问题,setAttribute()设置在IE7中,无法设置style等属性。这样就对设置样式带了很大的困扰,例如绑定点击事件来隐藏元素,setAttribute(”style“,”dispaly:none“);就可以解决,结果IE7 则无法生效。

关于解决兼容性的办法:

方法一:可以用dom的方法来设置Element的属性

例如前面提到的Element.setAttribute("Style","display:none;");

Element.style.display="none"; //dom赋值模式

Element.style.cssText="display:none;border:red solid 1px"//使用cssText  

cssText 属性是一组样式属性及其值的文本表示。这个文本格式化为一个 CSS 样式表,去掉了包围属性和值的元素选择器的花括号。

实例:隐藏内容

<body>

<a href="#" id="home">网站首页</a>

<script type="text/JavaScript">

  document.getElementById("home").setAttribute("Style","display:none;");//IE7下有问题

  document.getElementById("home").style.display="none";//建议方式

  document.getElementById("home").style.cssText="display:none;";//建议方式

</script>

</body>

setAttribute属性在为html标签添加class样式时也存在兼容性的问题

setAttribute("class”, value)这样在火狐中是可以实现的,但是在IE7上却存在问题,要使用setAttribute("className", value),而className火狐上又不识别,所以在兼容处理时,要写上两条语句。

Element.setAttribute("class", value);//for firefox

Element.setAttribute("className", value); //for IE7

或者  

Element.className=value;//for IE7

这样就很好的处理js中setAttribute的兼容性问题。

方法二:innerHTML 方法设置且替换

前面的例子修改为下面内容解决兼容问题:

 document.getElementById("home").innerHTML="<a href="#" id="home" style="display:none;">网站首页</a>";

但是注意,innerHTML也会存心新的兼容性问题:

使用时发现IE下在给tbody的innerHTML赋值时,js报错。因为innerHTML属性在IE下是只读的,因此在希望修改tbody的内容时,如果直接给tbody的innerHTML赋值,在IE下会报错。

当然,也可以使用一些跨平台的js框架,如jQuery

$("#objid").html(content);//它背后实现函数,兼容了各个浏览器的不同

在IE下,其它innerHTML是只读属性的标签列表

COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR

javascript中的setAttribute()浏览器的兼容性问题

1.element要用getElementById or ByTagName来得到,

2.setAttribute("class", vName)中class是指改变"class"这个属性,所以要带引号。
3.IE中要把class改成className,.....IE不认class,所以最好写两句,都用上吧。
W3C DOM - {setAttribute()}
setAttribute(string name, string value):增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。

1、关于class和className
class属性在W3C DOM中扮演着很重要的角色,但由于浏览器差异性仍然存在。使用setAttribute("class", vName)语句动态设置
Element的class属性在firefox中是行的通的,在IE中却不行。因为使用IE内核的浏览器不认识"class",要改用"className";
同样,firefox 也不认识"className"。所以常用的方法是二者兼备:
   element.setAttribute("class", vName);
   element.setAttribute("className", vName);  //for IE

2、setAttribute()的差异
我们经常需要在JavaScript中给Element动态添加各种属性,这可以通过使用setAttribute()来实现,这就涉及到了浏览器的兼容性问题。
var bar = document.getElementById("foo");
bar.setAttribute("onclick", "javascript:alert('This is a test!');");
这里利用setAttribute指定e的onclick属性,简单,很好理解。但是IE不支持,IE并不是不支持setAttribute这个函数,
而是不支持用setAttribute设置某些属性,例如对象属性、集合属性、事件属性,也就是说用setAttribute设置style和onclick这些属性
在IE中是行不通的。为达到兼容各种浏览器的效果,可以用点符号法来设置Element的对象属性、集合属性和事件属性。
document.getElementById("foo").className = "fruit";
document.getElementById("foo").style.cssText = "color: #00f;";
document.getElementById("foo").style.color = "#00f";
document.getElementById("foo").onclick= function () { alert("This is a test!"); }

原文地址:https://www.cnblogs.com/yangjing1314/p/6781266.html