Javascript多种浏览器兼容写法分析第1/3页_Javascript教程-查字典教程网
Javascript多种浏览器兼容写法分析第1/3页
Javascript多种浏览器兼容写法分析第1/3页
发布时间:2016-12-30 来源:查字典编辑
摘要:示例代码:不吃苹果尽量采用W3CDOM的写法以前访问对象可能是:document.all.apple或者apple现在应该采用:docume...

示例代码:

<body>

<table border="1" cellspacing="0" cellpadding="0" id="apple" >

<tbody>

<tr>

<td id="banana" >不吃苹果</td>

</tr>

</tbody>

</table>

</body>

尽量采用W3C DOM 的写法

以前访问对象可能是:

document.all.apple 或者 apple

现在应该采用:

document.getElementById("apple") 以ID来访问对象,且一个ID在页面中必须是唯一的

document.getElementsByTagName("div")[0] 以标签名来访问对象

原来设置对象的属性可能是:

document.all.apple.width=100 或 apple.width=100

现在应该采用:

document.getElementById("apple").setAttribute("width","100")

document.getElementsByTagName("div")[0].setAttribute("width","100")

访问对象的属性则采用:

document.getElementById("apple").getAttribute("width")

document.getElementsByTagName("div")[0].getAttribute("width")

W3C DOM在IE下的一些限制

因为起先的IE占据整个浏览器95%的份额,没有竞争压力,所以这位老大就硬是要玩点另类,不完全按WEB标准来搞。

在IE下不能正确使用setAttribute来设置对象的style、class以及事件响应属性,

因此我还得按原来的点记法来访问和设置,以达到兼容各种浏览器的效果,如:

document.getElementById("banana").class

document.getElementById("banana").style.color

document.getElementById("banana").onclick

document.getElementById("banana").class="fruit"

document.getElementById("banana").style.color="blue"

document.getElementById("banana").onclick= function (){alert("我是香蕉")}

关于Firefox下的onload问题

function over(){

alert("页面加载完毕")

}

正常情况下,我们赋与onload响应函数是:

document.body.onload= over

但是在Firefox下这样无法执行,

所以我们都都采用下面这种形式:

window.onload=over

关于IE下TABLE无法插入新行的问题

IE下TABLE无论是用innerHTML还是appendChild插入<tr>都没有效果,而其他浏览器却显示正常。解决他的方法是,将<tr>加到TABLE的<tbody>元素中,如下面所示:

var row = document.createElement("tr");

var cell = document.createElement("td");

var cell_text = document.createTextNode("香蕉不吃苹果");

cell.appendChild(cell_text);

row.appendChild(cell);

document.getElementsByTagName("tbody")[0].appendChild(row);

当前1/3页123下一页阅读全文

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类