<!-- 在介绍JavaScript的书籍和平时的代码积累中总结出的实用性比较强的代码 -->
<!-- 以下代码的编码格式为 UTF-8 -->

<!-- 作者：李蒙 -->
<!-- 日期：2007-12-22 -->

<!--#########################-->
<!--- 摘自《JavaScript精粹》 ---!>

<!-- 根据浏览器判断加载方法。并且在页面打开的时候可以加载多个函数 第一章--!>
function public_addLoadListener(fn)
{<!-- 参数fn是需要加载的函数的名称，具体应用事例参考《JavaScript精粹》 -->
  if (typeof window.addEventListener!='undefined')
   {
     window.addEventListener('load',fn,false);
   }
  else if (typeof document.addEventListener!='undefined')
   {
     document.addEventListener('load',fn,false);
   }
  else if (typeof window.attachEvent!='undefined')
   {
     window.attachEvent('onload', fn);
   }
  else
   {
     var oldfn=window.onload;
	 if (typeof window.onload!='function')
	  {
        window.onload=fn;
	  }
	 else
	  {
        window.onload=fuction()
		 {
           oldfn();
		   fn();
		 };
	  }
   }
}//end function addLoadListener(fn)


<!-- 获得拥有特定属性值的所有元素 第五章 -->
function public_getElementsByAttribute(attribute,attributeValue)
{
  var elementArray  =  new Array();
  var matchedArray  =  new Array();
  
  if (document.all)
   {
     elementArray = document.all;
   }//end if
  else
   {
     elementArray = document.getElementsByTagName("*");
   }//end else
  
  for (var i=0;i<elementArray.length;i++)
   {
     if (attribute=="class")
	  {
	    var pattern = new RegExp("(^| )" + attributeValue + "( |$)");
		if (pattern.test(elementArray[i].className))
		 {
		   matchedArray[matchedArray.length] = elementArray[i];
		 }
	  }//end if (attribute=="class")
	  
	 else if (attribute=="for")
	  {
	    if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for"))
		 {
		   if (elementArray[i].htmlFor==attributeValue)
		    {
			  matchedArray[matchedArray.length] = elementArray[i];
			}
		 }//end if (matchedArray[i].getAttribute("htmlFor") || elementArray[i].getArraybute("for"))
	  }//end else if (attribute=="for")
	 
	 else if (elementArray[i].getAttribute(attribute)==attributeValue)
	  {
	    matchedArray[matchedArray.length] = elementArray[i];
	  }
	 
   }//end for
   
  return matchedArray;
   
}//end function getElementsByAttribute()


<!-- 获取滚动位置 第七章 -->
function public_getScrollingPosition()
{
  var position = [0,0];
  if (typeof window.pageYOffset != "undefined")
   {
     position = [window.pageXOffset,window.pageYOffset];
   }//end if (typeof window.pageYOffset != "undefined")
  else if (typeof document.documentElement.scrollTop != "undefined" && document.documentElement.scrollTop>0)
   {
     position = [document.documentElement.scrollLeft,document.documentElement.scrollTop];
   }//end else if
  else if (typeof document.body.scrollTop != "undefined")
   {
     position = [document.body.scrollLeft,document.body.scrollTop];
   }//end else if
  
  return position;
}//end funciton


<!-- 识别特殊浏览器 第十一章 -->
function public_identifyBrowser()
{
  var agent = navigator.userAgent.toLowerCase();
  
  if (typeof navigator.vendor != "undefined" && navigator.vendor == "KDE" && typeof window.sidebar != "undefined")
   {
     return "kde";
   }//end if
  else if (typeof window.opera != "undefined")
   {
     var version = parseFloat(agent.replace(/.*opera[\/ ]([^ $]+).*/, "$1"));
	 
	 if (version >= 7)
	  {
        return "opera7";
	  }//end if
	 else if (version >= 5)
	  {
	    return "opera5";
	  }
	 
	 return false;
   }//end else if
  else if (typeof document.all != "undefined")
   {
	 if (typeof document.getElementById != "undefined")
	  {
	    var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, "$1").replace(/ /, "");
		if (typeof document.uniqueID != "undefined")
		 {
	       if (browser.indexOf("5.5") != -1)
		    {
		      return browser.replace(/(.*5\.5).*/, "$1");
			}//end if
		   else
		    {
			  return browser.replace(/(.*)\..*/, "$1");
			}//end else
		 }//end if
		else
		 {
	       return "ie5mac";
		 }//end else
	  }//end if
	  
	 return false;
   }//end else if
  else if (typeof document.getElementById != "undefined")
   {
     if (navigator.vendor.indexOf("Apple Computer, Inc.") != -1)
	  {
	    if (typeof window.XMLHttpRequest != "undefined")
		 {
	       return "safari1.2";
		 }//end if
		
		return "safari1";
	  }//end if
	 else if (agent.indexOf("gecko") != -1)
	  {
	    return "mozilla";
	  }//end else if
   }//end else if
   
  return false;
}//end function


<!-- 检测浏览器运行在什么操作系统下 第十一章 -->
function public_indetifyOS()
{
  var agent = navigator.userAgent.toLowerCase();

  if (agent.indexOf("win") != -1)
   {
     return "win";
   }//end if
  else if (agent.indexOf("mac"))
   {
     return "mac";
   }//end else if
  else
   {
     return "unix";
   }//end else
  
  return false;
}//end function


<!-- 禁止默认动作的发生 第十三章 -->
function public_stopDefaultAction(event)
{
  event.returnVaule = false;
  
  if (typeof event.preventDefault != "undefined")
   {
     event.preventDefault();
   }//end if
}//end function


<!-- 寻找最初分配事件监听者的元素 第十三章 -->
function public_getEventTarget(event)
{
  var targetElement = null;
  
  if (typeof event.target != "undefined")
   {
     targetElement = event.target;
   }//
  else
   {
     targetElement = event.srcElement;
   }
  
  while (targetElement.nodeType == 3 && targetElement.parentNode != null)
   {
     targetElement = targetElement.parentNode;
   }//end while
   
  return targetElement;
}//end function


<!-- W3C标准方法：使用事件监听者 第十三章 -->
<!-- 具体事例请参考《JavaScript精粹》第十四章 -->
function public_attachEventListener(target,eventType,functionRef,capture)
{
  if (typeof target.addEventListener != "undefined")
   {
     target.addEventListener(eventType,functionRef,capture);
   }//end if
  else if (typeof target.attachEvent != "undefined")
   {
	 var functionString = eventType + functionRef;
	 target["e" + functionString] = functionRef;

	 target[functionString] = function(event)
	  {
	    if (typeof event == "undefined")
		 {
	       event = window.event;
		 }//end if
		target["e" + functionString](event);
	  };//end function()
	 
     target.attachEvent("on"+eventType,target[functionString]);
   }//end else if
  else
   {
     eventType = "on"+eventType;
	 if (typeof target[eventType] == "function")
	  {
	    var oldListener = target[eventType];
		target[eventType] = function()
		 {
	       oldListener();
		   return functionRef();
		 };//end function()
	  }//end if
	 else
	  {
	    target[eventType] = functionRef;
	  }//end else
   }//end else
}//end function


<!-- W3C标准方法：去除事件监听者 第十三章 -->
<!-- 具体事例请参考《JavaScript精粹》第十四章 -->
function public_detachEventListener(target,eventType,functionRef,capture)
{
  if (typeof target.removeEventListener != "undefined")
   {
     target.removeEventListener(eventType,functionRef,capture);
   }//end if
  else if (typeof target.detachEvent != "undefined")
   {
	 var functionString = eventType + functionRef;
	 
	 target.detachEvent("on" + eventType,target[functionString]);
	 
	 target["e" + functionString] = null;
	 target[functionString] = null;
   }//end else if
  else
   {
     target["on" + eventType] = null;
   }
}//end function


<!-- W3C标准方法：终止监听事件 第十三章 -->
function public_stopEvent(event)
{
  if (typeof event.stopPropagation != "undefined")
   {
     event.stopPropagation();
   }//end if
  else
   {
	 event.cancelBubble = true;
   }//end else
}//end function


<!-- 获取元素的位置 第十三章 -->
function public_getPosition(theElement)
{
  var positionX = 0;
  var positionY = 0;
  
  while (theElement != null)
   {
     positionX += theElement.offsetLeft;
	 positionY += theElement.offsetTop;
	 theElement = theElement.offsetParent;
   }//end while
   
  return [positionX,positionY];
}//end function public_getPosition(theElement)


<!-- 检测鼠标光标的位置 第十三章 -->
function public_displayCursorPosition(event)
{
  if (typeof event == "undefined")
   {
     event = window.event;
   }//end if
  
  var scrollingPosition = public_getScrollingPosition();
  var cursorPosition = [0,0];
  
  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
   {
     cursorPosition[0] = event.pageX;
	 cursorPosition[1] = event.pageY;
   }//end if
  else
   {
     cursorPosition[0] = event.clientX + scrollingPosition[0];
     cursorPosition[1] = event.clientY + scrollingPosition[1];
   }//end else

  //var paragraph = document.getElementsByTagName("p")[0];
  //paragraph.replaceChild(document.createTextNode("your mouse is currently located at: " +cursorPosition[0] +","+ cursorPosition[1]),paragraph.firstChild)
  
  return cursorPosition;
}//end function public_displayCursorPosition(event)


<!-- 根据class属性得到标签 -->
function public_getElementsByClass(object, tag, className)
{
  var o = object.getElementsByTagName(tag);
  for ( var i = 0, n = o.length, ret = []; i < n; i++)
  {
	if (o[i].className == className) ret.push(o[i]);
  }
  if (ret.length == 1) ret = ret[0];
  return ret;
}


<!--得到HTML标签的元素的id-->
function public_getObject(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
return document.getElementById(objectId);
} else if (document.all && document.all(objectId)) {
return document.all(objectId);
} else if (document.layers && document.layers[objectId]) {
return document.layers[objectId];
} else {
return false;
}
}//end function getObject(objectId)




<!--###############-->
<!--检查表单-->
function public_CheckForm(oForm)
{
var els = oForm.elements;
for(var i=0;i<els.length;i++)
{
if(els[i].check)
{
var sReg = els[i].check;
var sVal = GetValue(els[i]);
var reg = new RegExp(sReg,"i");
if(!reg.test(sVal))
{
alert(els[i].warning);
GoBack(els[i])
return false;
}
}
}
}
function GetValue(el)
{
var sType = el.type;
switch(sType)
{
case "text":
case "hidden":
case "password":
case "file":
case "textarea": return el.value;
case "checkbox":
case "radio": return GetValueChoose(el);
case "select-one":
case "select-multiple": return GetValueSel(el);
}
function GetValueChoose(el)
{
var sValue = "";
var tmpels = document.getElementsByName(el.name);
for(var i=0;i<tmpels.length;i++)
{
if(tmpels[i].checked)
{
sValue += "0";
}
}
return sValue;
}
function GetValueSel(el)
{
var sValue = "";
for(var i=0;i<el.options.length;i++)
{
if(el.options[i].selected && el.options[i].value!="")
{
sValue += "0";
}
}
return sValue;
}
}

function GoBack(el)
{
var sType = el.type;
switch(sType)
{
case "text":
case "hidden":
case "password":
case "file":
case "textarea": el.focus();var rng = el.createTextRange(); rng.collapse(false); rng.select();
case "checkbox":
case "radio": var els = document.getElementsByName(el.name);els[0].focus();
case "select-one":
case "select-multiple":el.focus();
}
}//function CheckForm(oForm)

<!--####################################################-->
<!--　AJAX -->
function public_InitAjax()
{
  var ajax=false; 
  try
  { 
    ajax = new ActiveXObject("Msxml2.XMLHTTP"); 
  }
  catch (e)
  { 
    try
    { 
      ajax = new ActiveXObject("Microsoft.XMLHTTP"); 
    }
    catch (E)
    { 
      ajax = false; 
    } 
  }
  if (!ajax && typeof XMLHttpRequest!='undefined')
  { 
    ajax = new XMLHttpRequest(); 
  } 
  return ajax;
} 


function getdiy(diyID)//AJAX用法示例
{
  if (typeof(diyID) == 'undefined')
  {
  　return false;
  }
  var url = "diypage.php?diyid="+ diyID;
  var show = document.getElementById("diy"); 
  //var show2= document.getElementById("ifile");alert(show2.id+'xxx');
  var ajax = public_InitAjax();
  ajax.open("GET", url, true); 
  ajax.onreadystatechange = function()
  { 
    if(ajax.readyState<4)
    {
      document.getElementById("diy").innerHTML = "正在加载....请稍等";
    }

    if (ajax.readyState == 4 && ajax.status == 200)
    { 
　    show.innerHTML = ajax.responseText;
      //document.getElementById("diy").innerHTML ="";
      //alert(ajax.responseText);
      //show2.setAttribute("src",ajax.responseText);
    } 
  }
  ajax.send(null); 
} //function getdiy(diyID)


	
<!--#####################-->
<!--另一个iframe自动适应页面的代码，更简单。下面是例子：主要是onload后面的代码-->
<!-- 参数parent的作用是：如果引用该函数的位置在iframe的里面，需要把parent的值设置为'parent' -->
<!--<iframe name=\"file\" id=\"file\" border=0 frameborder=no  width=\"800\"  marginheight=0 marginwidth=0 scrolling=\"auto\" src=\" check/dateinterval_check.php\" allowTransparency=\"true\" onload='var f=document.all[\"file\"];   var   b=f.Document.body;   f.height=b.scrollHeight+10'></iframe>-->
function public_iframeAdapt(iframename, theparent)
{
  if (theparent == 'parent')
  {
   var f=parent.document.all[iframename];   
  }
  else
  {
   var f=document.all[iframename];   
  }
  
  //var f=public_getObject(iframename);   //alert(typeof f);
  var browser = public_identifyBrowser();
  //alert(browser);
  if (browser == "opera7")
  {  
    var b=f.document.body;
  }
  else if (browser == "mozilla")
  {
    var b=f.contentDocument.body;
  }
  else if (browser == 'safari1.2')
  {
    var b=f.contentDocument.body;
  }
  else
  {
    var b=f.Document.body;
  }
  
  //f.style.height=b.scrollHeight+20;
  f.style.height=b.scrollHeight;
  //alert("b.scrollHeight="+b.scrollHeight+"  f.height="+f.height);
}

<!-- 替换字符串中的&符号 -->
<!-- 从js中读取数据中用到，用ajax传递到服务器端用php的函数替换回去 -->
function public_SymbolANDEncode(string)
{
  var pattern = /&/g;
  var result = string.replace(pattern,'[@symbol_AND]');
  return result;
}//end function

<!-- 把字符串中的&amp;替换成& -->
function public_replaceSymbolAND(string)
{
  var pattern = /&amp;/g;
  var result = string.replace(pattern,'&');
  return result;
}//end function
<!-- 把字符串中的&替换成&amp; -->
function public_replaceSymbolAND2(string)
{
  var pattern = /&/g;
  var result = string.replace(pattern,'&amp;');
  return result;
}//end function

<!-- 简单实用的函数 -->
<!-- 显示id=getid的元素 -->
function public_displaySet(getid)
{
  public_getObject(getid).style.display = '';
}//end function
<!-- 隐藏id=getid的元素 -->
function public_hideSet(getid)
{
  public_getObject(getid).style.display = 'none';
}//end function
<!-- 隐藏id=getid的元素的另一种方法：把这个元素放到屏幕的外边 -->
function public_leaveSet(getid)
{
  public_getObject(getid).style.left = '-2000px';
}//end function

<!-- 字体加粗 -->
function public_fontBold(getid)
{
  public_getObject(getid).style.fontWeight = 'bold';
}//end function
<!-- 字体还原 -->
function public_fontNormal(getid)
{
  public_getObject(getid).style.fontWeight = '';
}//end function
<!-- 背景图片变化 -->
function public_bgImageChange(getid,imgpath)
{
  if (imgpath == '' || imgpath == 'none')
  {
    return false;
  }
  
  public_getObject(getid).style.backgroundImage = 'url("'+ imgpath +'")';
}//end function

<!-- 设置Cookie -->
function public_setCookie(name,value,t)
{
	var cookieexp = 5*30*24*60*60*1000; //5 months
	var cookiestr=name+"="+escape(value)+";";
	var expires = "";
	var d = new Date();
	var t2=(!t)?cookieexp:t*60*1000;
	d.setTime( d.getTime() + t2);
	expires = "expires=" + d.toGMTString()+";";
	document.cookie = cookiestr+ expires;
}
<!-- 取得Cookie -->
function public_getCookie(name)
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) return "";
	if ( start == -1 ) return "";
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

