使 Web 应用程序能够适应多种浏览器
在不同的浏览器或具有不同设置的浏览器上,Web 页面的执行方式不一样。本文学习一些有用的技巧,帮助您让自己的 Web 应用程序更适应所有的环境。
不同 Web 浏览器的特性,比如语言设置和 JavaScript 支持,会导致 Web 应用程序在不同浏览器中的工作方式不一致。浏览器之间的不一致性不但会导致应用程序看起来很糟糕,而且常常使它无法工作。本文将给出一些技巧,您可以使用这些技巧解决这类问题。
Web 页面无法在任何地方都顺利工作的主要原因是,不同种类的浏览器支持不同的标准。克服这个问题的最佳方法是只使用通用的属性和方法。但是,有时候必须编写特殊的代码。
使用 innerText 属性设置或获取在一个对象的开始标记和结束标记之间的文本,这个属性只在 Microsoft® Windows® Internet Explorer® 中定义了。尽管这个属性得到了广泛的使用,但它不是标准属性。可以使用 innerHTML 替代它,但是它们并不相同。innerText 属性提供了特殊特性,比如能够直接获得子节点的文本,这可以帮助我们编写更干净的代码。您也可能遇到使用 innerText 属性的遗留页面。通过自己实现 innerText 属性,可以让这些页面支持更多的浏览器。例如,可能需要在基于 Mozilla 的浏览器中实现这个属性;清单 1 展示了实现方法。
清单 1. 为基于 Mozilla 的浏览器实现 innerText
HTMLElement.prototype.__defineGetter__
(
"innerText",function()
//define a getter method to get the value of innerText,
//so you can read it now!
{
var textRange = this.ownerDocument.createRange();
//Using range to retrieve the content of the object
textRange.selectNodeContents(this);
//only get the content of the object node
return textRange.toString();
// give innerText the value of the node content
}
);
|
大多数 Web 应用程序需要几何值,比如窗口大小和滚动值。但是,浏览器可以在不同的属性中存储这些值;一些属性甚至是名称相同而含义不同。更好的方法是创建自己的独特的变量来表示这些属性值。清单 2 演示了如何在多数主流浏览器中创建独特的属性。
清单 2. 将一些通用变量定义为独特的属性,可以用来存储几何值
var scrollLeft,scrollTop;
// scrollLeft: The distance between the horizontal scrollbar
// with the left edge of the frame.
// scrollTop: The distance between the vertical scrollbar
// with the top edge of the frame.
// Get the scroll value from different browsers.
// Determine the browser type first.
// And then get the value from the particular property.
if (window.pageYOffset){
scrollTop = window.pageYOffset
} else if(document.documentElement && document.documentElement.scrollTop){
scrollTop = document.documentElement.scrollTop;
} else if(document.body){
scrollTop = document.body.scrollTop;
}
if(window.pageXOffset){
scrollLeft=window.pageXOffset
} else if(document.documentElement && document.documentElement.scrollLeft){
scrollLeft=document.documentElement.scrollLeft;
} else if(document.body){
scrollLeft=document.body.scrollLeft;
}
var windowWidth,windowHeight; // frame width & height
if(window.innerWidth){
windowWidth=window.innerWidth;
} else if(document.documentElement && document.documentElement.clientWidth){
windowWidth=document.documentElement.clientWidth;
} else if(document.body){
windowWidth=document.body.offsetWidth;
}
if(window.innerHeight){
windowHeight=window.innerHeight;
} else if(document.documentElement && document.documentElement.clientHeight){
windowHeight=document.documentElement.clientHeight;
} else if(document.body){
windowHeight=document.body.clientHeight;
}
|
一些语言(比如 Arabic 和 Hebrew)被称为双向语言,这意味着它们是从右到左阅读的。当前的浏览器支持从右到左显示内容。但是,当页面从右到左显示时,Internet Explorer 定义了不同的窗口原点。这个原点并不在画布的左上角,而是在可见部分的左上角。这意味着页面的某些部分会有负的 x 值,这会使页面的某些元素出现在错误的位置上。图 1 显示当页面从右到左显示时 Internet Explorer 中原点的位置。
图 1. 当页面从右到左显示时 Internet Explorer 中的原点
请记住,当页面在 Internet Explorer 中从右到左显示时,必须修改算法,比如按照原点的偏移量调整元素的位置。

浙公网安备 33010602011771号