|
Jun
13
|
1. 通过JavaScript设置元素的样式
通过元素(Element)的setAttribute()方法设置style属性:
var testdiv = document.getElementById("testdiv");
testdiv.setAttribute("style", "font-size:24px;color:red;");
除了IE(Microsoft Internet Explorer),这种方法在当前其它浏览器上都行得通。为了照顾IE,我们可以使用设置不标准的属性—元素style对象的cssText属性。尽管这个属性不是标准的,但得到了广泛的支持(除了Opera):
var testdiv = document.getElementById("testdiv");
testdiv.style.cssText = "font-size:24px;color:red;";
- Firefox等浏览器:运行代码,在下面的测试区域查看效果。
-
Firefox等浏览器IE浏览器:
,在下面的测试区域查看效果。
2. 设置元素的class属性
使用Firefox和Safari之类的浏览器,可以通过元素(Element)的setAttribute()方法设置class属性:
var testdiv = document.getElementById("testdiv");
testdiv.setAttribute("class", "cat");
为了照顾IE这个异类,它只认识className属性—在IE中className = class,其它大多数浏览器都忽略className属性。你可以这样做:
var testdiv = document.getElementById("testdiv");
testdiv.setAttribute("class", "cat");
testdiv.setAttribute("className", "cat");
这里是测试用的区域:
测试用的区域。Hello world!
上面的代码已经在Mozilla Firefox 1.5.0.2,Opera 8.54,Konqueror 3.5.2,IE6 测试通过。
3. 创建输入元素
注意document.createElement()和<Element>.setAttribute()方法的顺序:
var button = document.createElement("input");
button.setAttribute("type", "reset");
var testdiv = document.getElementById("testdiv").appendChild(button);
- Firefox等浏览器和IE浏览器:运行代码,在测试区域查看效果。
4. 向元素增加事件处理
标准的做法是:
var testdiv = document.getElementById("testdiv");
testdiv.setAttribute("onclick", "doFoo();");
除了IE,上面的代码在所有的当前浏览器中都能工作。在IE中必须使用点词法来引用所需的事件处理程序:
var testdiv = document.getElementById("testdiv");
testdiv.onclick = function(){doFoo();};
相关资源:
- 《Ajax基础教程》纸质书—人民邮电出版社。
- World Wide Web Consortium (W3C)
- Document Object Model (DOM)
- ECMAScript [ECMAScript] binding for the Level 3 Document Object Model Core definitions.
- The XMLHttpRequest Object
- The Document Object Model in Mozilla and The Mozilla DOM Reference: all objects, properties and methods (Zipped HTML)
- ajaxian.com
Related posts:
3 Responses to “开发跨浏览器JavaScript—《Ajax基础教程》笔记”
Pages:
Leave a Reply

2006-06-14 at 14:29:27
测试区域放在最下面不太方便哈~
2006-06-14 at 14:45:12
回复K:
谢谢提醒,我已经重新排版。把测试区域放到文章的中间位置。
2006-06-15 at 18:23:52
呵呵,反映真快~
我们看的是同一本书(你也是图书馆的吗?),一起学习啊~