Home > Web Front-end > JS Tutorial > body text

IE6、IE7中setAttribute不支持class/for/rowspan/colspan等属性_javascript技巧

WBOY
Release: 2016-05-16 18:03:01
Original
1078 people have browsed it

如设置class属性

复制代码 代码如下:
el.setAttribute('class', 'abc');

在IE6/7中样式“abc”将没有起作用,虽然使用el.getAttribute('class')能取到值“abc”。

又如for属性
复制代码 代码如下:


<script> <BR>var lab = document.getElementsByTagName('label')[0]; <BR>lab.setAttribute('for', 'name'); <BR></script>

我们知道当lab设置了for属性,点击label将自动将对应的checkbox选中。但以上设置在IE6/7点击将不会选中checkbox。

类似的情况还发生在 cellspacing/cellpadding 上。汇总如下:
class
for
cellspacing
cellpadding
tabindex
readonly
maxlength
rowspan
colspan
usemap
frameborder
contenteditable
因此,当写一个通用的跨浏览器的设置元素属性的接口方法时需要考虑注意以上属性在IE6/7中的特殊性。如下
复制代码 代码如下:

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));
}
}
})();

首先,标准浏览器直接使用原始属性名;其次,IE6/7非以上列举的属性仍然用原始属性名;最后这些特殊属性(与JS关键字同名如for,class)使用fixAttr。
好了,现在不用考虑className/htmlFor了,都使用class/for即可。
复制代码 代码如下:

dom.setAttr(el, 'class', 'red');
dom.getAttr(el, 'class');
dom.setAttr(el, 'for', 'userName');
dom.getAttr(el, 'for');
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!