2006-06-13

开发跨浏览器JavaScript—《Ajax基础教程》笔记

Views: 14998 | 3 Comments

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");
  • Firefox等浏览器:运行代码,在下面的测试区域查看效果。
  • Firefox等浏览器IE浏览器:运行代码,在下面的测试区域查看效果。

这里是测试用的区域:

测试用的区域。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();};

相关资源:

Related posts:

  1. 用Javascript生成弹出窗口
  2. 最简单的JavaScript两级联动示例
  3. 清除Web标准误区,保持清晰的文档结构
  4. 用 HBase 来存储 zset
  5. CSS 样式规则的匹配算法实现
Posted by ideawu at 2006-06-13 10:27:29 Tags:

3 Responses to "开发跨浏览器JavaScript—《Ajax基础教程》笔记"

Leave a Comment