JavaScript,IE與非IE之間的差別(未完待續)

var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1 ? true : false;
var isIE9 = /msie\s+9/i.test(navigator.userAgent);

//1.float
if(isIE){
	document.getElementById("block").style.styleFloat = "right";
}else{
	document.getElementById("block").style.cssFloat = "right";
}

//2.計算出的樣式
if(isIE){
	var currentStyle = document.getElementById("block").currentStyle.backgroundColor;
	console.log(currentStyle);
}else{
	var dom = document.getElementById("block");
	var currentStyle = document.defaultView.getComputedStyle(dom,null).backgroundColor;
	console.log(currentStyle);
}

//3.獲取光標位置
if(isIE){
	var dom = document.getElementById("block");
	dom.onmouseover = function(event){
      if(isIE9){
				console.log(event.pageX);
				return;
			}
			event = event || window.event;
			console.log(event.clientX);
	}
}else{
	var dom = document.getElementById("block");
	dom.onmouseover = function(event){
		console.log(event.pageX);
	}
}

//4.獲取視窗或瀏覽器窗口的尺寸
if(isIE){
	var browerSize = {};
	browerSize.screenX = document.documentElement.clientWidth;
	browerSize['screenY'] = document.documentElement.clientHeight;
	console.log(browerSize);
}else{
	var browerSize = {};
	browerSize.screenX = window.innerHeight;
	browerSize['screenY'] = window.innerWidth;
}

//5.註冊事件
if(isIE){
	var elem = document.getElementById("hit");
	elem.attachEvent("onclick",function(event){
		event = event || window.event;
		//事件源
		console.log(event.srcElement);
		//事件傳播
		event.cancelBubble = true;
		//阻止默認行為
		event.returnValue = false;
	});
}else{
	var elem = document.getElementById("hit");
	elem.addEventListener("click",function(event){
		//事件源
		console.log(event.target && event.srcElement);
		//事件傳播
		event.stopPropagation();
		//阻止默認行為
		event.preventDefault();
	},false);
}

//6.獲取對象層次中的父對象,IE:parentElement
var parent = function(elem){
  elem = document.getElementById(elem);
	return elem.parentElement && elem.parentNode;
}

//7.獲取作為指定對象直接後代的 HTML 元素和TextNode對象的集合
var getChildren = function(elem){
	elem = document.getElementById(elem);
	return elem.childNodes && elem.children;
}

//8.DOM加載完畢
if(isIE){
	document.attachEvent("onreadystatechange",function(){
		console.log("IE DOM ready");
	})
}else{
	document.addEventListener("DOMContentLoaded",function(){
		console.log("Webkit DOM ready");
	},false);
}

 

發佈留言