项目的页面要求javascript在IE、火狐(Firefox)和谷歌(Google Chrome)三个浏览器中都能运行,期间遇到一些问题,现收集并总结一些:
1.获取鼠标的坐标时,使用event.clientX,不要使用event.x,因为火狐不支持event.x,最好使用event.screenX。
2.火狐中不能在js中直接使用event对象,必须将event传递给js方法再使用。例:
<input name=”username” onclik=”alertMsg(event)”/>
function alertMsg(eventObj)
{
alert(eventObj.clientX);
}
3.火狐和谷歌在给obj.style.left和obj.style.top赋值时加上单位px,例:obj.style.left=100px。IE中可不加单位。
4.IE中增加事件用attachEvent,例:window.attachEvent(“onscroll”, functioname); 火狐和谷歌则用addEventListener,例:window.addEventListener(“scroll”,functioname, false);
5.火狐和IE中可以用document.documentElement.scrollTop获取滚动的高度,而在谷歌里要用document.body.scrollTop。
6.火狐和谷歌中不支持DIV的onresize事件
7.改变table的高度用table.style.height=”100px”,因为火狐和谷歌不支持table.height=”100px“这种写法。
8.动态添加文本时不要用innerText,用innerHTML,因为火狐用innerText在页面上看不到文本。
9.获取表单对象时用document.formname,不要直接写formname,因为在火狐上获取不到。
10。文本框获取光标。当文本框有值时。在IE中光标会在文字前面。但在谷歌。和火狐默认都是在后面。IE中可以这样:
因为只适合IE,所以判断是否是IE
function setFocus() {
if (navigator.userAgent.indexOf("MSIE") > 0) {
var obj = event.srcElement; //ff中。这里是空
var txt = obj.createTextRange();
txt.moveStart('character', obj.value.length);
txt.collapse(true);
txt.select();
}
}
11.IE6中position :fixed 定位
.fixed
{
_left: 350px;
_position: absolute;
_top:expression(eval(document.documentElement.scrollTop));
}
然后不想让屏幕抖动
*html
{
background-image: url(about:blank);
background-attachment: fixed;
}
/判断浏览器版本
function getExplorer() {
var explorer = window.navigator.userAgent;
//ie
if (explorer.indexOf("MSIE") >= 0) {
// name="select"
$("#CusTab [name=select]").css("width", 130 + "px");
}
//firefox
else if (explorer.indexOf("Firefox") >= 0) {
$("#CusTab [name=select]").css("width", 153 + "px");
}
//Chrome
else if (explorer.indexOf("Chrome") >= 0) {
// alert("Chrome");
}
//Opera
else if (explorer.indexOf("Opera") >= 0) {
//alert("Opera");
}
//Safari
else if (explorer.indexOf("Safari") >= 0) {
//alert("Safari");
}
}