DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript常用函數(2)
javascript常用函數(2)
編輯:關於JavaScript     

文章主要內容列表:
16、 除去數組重復項
17、 操作cookie
18、 判斷浏覽器類型
19、 判斷是否開啟cookie
20、 斷是否開啟JavaScript
21、 JavaScript 打字機效果
22、 簡單打印
23、 禁止右鍵
24、 防止垃圾郵件
25、復制(javaeye flash版)
26、 阻止冒泡事件或阻止浏覽器默認行為
27、 關閉或跳轉窗口時提示
28、 用javascript獲取地 址欄參數
29、 計算停留的時間
30、 div為空,只有背景時,背景自動增高 

主要內容:
16、除去數組重復項

<script> 
Array.prototype.remove = function(){ 
 var $ = this; 
 var o1 = {}; 
 var o2 = {}; 
 var o3 = []; 
 var o; 
 
 for(var i=0;o = $[i];i++){ 
  if(o in o1){ 
   if(!(o in o2)) o2[o] = o; 
   delete $[i]; 
  }else{ 
   o1[o] = o; 
  } 
 } 
 
 $.length = 0; 
 
 for(o in o1){ 
  $.push(o); 
 } 
 
 for(o in o2){ 
  o3.push(o); 
 } 
 
 return o3; 
 
} 
 
var a = [2,2,2,3,3,3,4,4,5,6,7,7]; 
 
a.remove (); 
 
document.write(a); 
 
</script> 

17、 操作cookie

// 1. 設置COOKIE 
 
// 簡單型 
 
function setCookie(c_name,value,expiredays) 
{ 
var exdate=new Date() 
exdate.setDate(exdate.getDate()+expiredays) 
 
document.cookie=c_name+ "=" +escape(value)+ 
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) 
} 
 
// 完整型 
function SetCookie(name,value,expires,path,domain,secure) 
{ 
var expDays = expires*24*60*60*1000; 
 
var expDate = new Date(); 
expDate.setTime(expDate.getTime()+expDays); 
 
var expString = ((expires==null) ? "" : (";expires=”+expDate.toGMTString())) 
var pathString = ((path==null) ? "" : (";path="+path)) 
var domainString = ((domain==null) ? "" : (";domain="+domain)) 
var secureString = ((secure==true) ? ";secure" : "" ) 
document.cookie = name + "=" + escape(value) + expString + pathString + domainString + secureString; 
} 
 
 
// 2.獲取指定名稱的cookie值: 
 
function getCookie(c_name) 
{ 
if (document.cookie.length>0) 
 { 
 c_start=document.cookie.indexOf(c_name + "=") 
 if (c_start!=-1) 
 { 
 c_start=c_start + c_name.length+1 
 c_end=document.cookie.indexOf(";",c_start) 
 if (c_end==-1) c_end=document.cookie.length 
 return unescape(document.cookie.substring(c_start,c_end)) 
 } 
 } 
return "" 
} 
 
 
// 3.刪除指定名稱的cookie: 
 
function ClearCookie(name) 
{ 
var expDate = new Date(); 
expDate.setTime(expDate.getTime()-100); 
 
document.cookie=name+”=;expires=”+expDate.toGMTString(); 
 
} 
 
// 4. 檢測cookie: 
 
function checkCookie() 
{ 
username=getCookie('username') 
if (username!=null && username!="") 
 {alert('Welcome again '+username+'!')} 
else 
 { 
 username=prompt('Please enter your name:',"") 
 if (username!=null && username!="") 
 { 
 setCookie('username',username,365) 
 } 
 } 
}

18、獲取坐標

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>payment</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head> 
 
<body style="font-size:12px;"> 
 
<script> 
var strInfo=""; 
strInfo += "網頁可見區域寬:" + document.body.clientWidth + "<br>"; 
strInfo += "網頁可見區域高:" + document.body.clientHeight + "<br>"; 
strInfo += "網頁可見區域寬:" + document.body.offsetWidth + "(包括邊線的寬)<br>"; 
strInfo += "網頁可見區域高:" + document.body.offsetHeight + "(包括邊線的寬)<br>"; 
strInfo += "網頁正文全文寬:" + document.body.scrollWidth + "<br>"; 
strInfo += "網頁正文全文高:" + document.body.scrollHeight + "<br>"; 
strInfo += "網頁被卷去的高:" + document.body.scrollTop + "<br>"; 
strInfo += "網頁被卷去的左:" + document.body.scrollLeft + "<br>"; 
strInfo += "網頁正文部分上:" + window.screenTop + "<br>"; 
strInfo += "網頁正文部分左:" + window.screenLeft + "<br>"; 
strInfo += "屏幕分辨率的高:" + window.screen.height + "<br>"; 
strInfo += "屏幕分辨率的寬:" + window.screen.width + "<br>"; 
strInfo += "屏幕可用工作區高度:" + window.screen.availHeight + "<br>"; 
strInfo += "屏幕可用工作區寬度:" + window.screen.availWidth + "<br>"; 
 
document.write(strInfo); 
</script> 
 
<br><br> 
<p> 
clientX 設置或獲取鼠標指針位置相對於窗口客戶區域的 x 坐標,其中客戶區域不包括窗口自身的控件和滾動條。 <br> 
clientY 設置或獲取鼠標指針位置相對於窗口客戶區域的 y 坐標,其中客戶區域不包括窗口自身的控件和滾動條。<br> 
offsetX 設置或獲取鼠標指針位置相對於觸發事件的對象的 x 坐標。<br> 
offsetY 設置或獲取鼠標指針位置相對於觸發事件的對象的 y 坐標。<br> 
screenX 設置或獲取獲取鼠標指針位置相對於用戶屏幕的 x 坐標。<br> 
screenY 設置或獲取鼠標指針位置相對於用戶屏幕的 y 坐標。<br> 
x 設置或獲取鼠標指針位置相對於父文檔的 x 像素坐標。<br> 
y 設置或獲取鼠標指針位置相對於父文檔的 y 像素坐標。<br> 
 
event.clientX返回事件發生時,mouse相對於客戶窗口的X坐標,event.X也一樣。<br> 
但是如果設置事件對象的定位屬性值為relative,event.clientX不變,而event.X返回事件對象的相對於本體的坐標。<br> 
</p> 
</body> 
</html> 

18、 判斷浏覽器類型
Js代碼

<script type="text/javascript"> 
  var Sys = {}; 
  var ua = navigator.userAgent.toLowerCase(); 
  var s; 
  (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : 
  (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] : 
  (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] : 
  (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] : 
  (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0; 
 
  //以下進行測試 
  if (Sys.ie) document.write('IE: ' + Sys.ie); 
  if (Sys.firefox) document.write('Firefox: ' + Sys.firefox); 
  if (Sys.chrome) document.write('Chrome: ' + Sys.chrome); 
  if (Sys.opera) document.write('Opera: ' + Sys.opera); 
  if (Sys.safari) document.write('Safari: ' + Sys.safari); 
 </script> 

jquery版

<script src="jquery-latest.js"></script> 
<script type="text/javascript">  
$(document).ready(function(){ 
 var bro=$.browser; 
 var binfo=""; 
 if(bro.msie) {binfo="Microsoft Internet Explorer "+bro.version;} 
 if(bro.mozilla) {binfo="Mozilla Firefox "+bro.version;} 
 if(bro.safari) {binfo="Apple Safari "+bro.version;} 
 if(bro.opera) {binfo="Opera "+bro.version;} 
 alert(binfo); 
}) 
</script> 

19、判斷是否開啟cookie

<script> 
 function checkCookie() { 
  var result=false; 
  if(navigator.cookiesEnabled){ return true; } 
  document.cookie = "testcookie=yes;"; 
 
  var setCookie = document.cookie; 
 
  if (setCookie.indexOf("testcookie=yes") > -1){ 
   result=true; 
  }else{ 
   document.cookie = ""; 
  } 
 
  return result; 
 } 
 
  if(!checkCookie()){ 
  alert("對不起,您的浏覽器的Cookie功能被禁用,請開啟");  
  }else{ 
  alert("Cookie 成功開啟"); 
  } 
</script> 
 

20、 斷是否開啟JavaScript

// 方案 1 
 
<span id="js_enable">您關閉了JavaScript</span> 
<script type="text/javascript"> 
<!-- 
 document.getElementById("js_enable").innerHTML='您開啟了JavaScript'; 
--> 
</script> 
 
// 方案 2 
 
<div id="NoJs" >您禁用了javascript。</div> 
<div id="YesJs" style="display:none;">您的Javascript是開啟的</div>  
<script>  
 var NoJs= document.getElementById("NoJs"); 
 var YesJs= document.getElementById("YesJs"); 
 NoJs.style.display="none"; 
 YesJs.style.display="block"; 
</script> 
 
// 方案 3 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>檢查浏覽器是否開啟JavaScript</title> 
</head> 
 
<body> 
如果您的浏覽器支持的話,本頁面什麼也不會顯示,如果不支持,則會出現提示! 
<noscript>  
<body scroll=no style="text-align: center"> 
<center> 
 <table border="0" style="height: 100%; width: 100%; right: 1%; left: 1%; background: black; position: fixed"> 
  <tr> 
   <td align="center"> 
    <div style="position: fixed; font-size: 18px; z-index: 2; cursor: help; background: #F8F8FF; width: 480px; color: black; padding: 5px 5px 5px 5px; border: 1px solid; border-color: maroon; height: auto; text-align: left; left: 20%"> 
    <span style="font: bold 20px Arial; color:#F8F8FF; background: maroon; vertical-align: middle">對不起,你的浏覽器沒有打開JavaScript腳本支持!</span></div> 
   </td> 
  </tr> 
 </table> 
</center> 
</noscript> 
</body> 
</html> 

 HTML <noscript> 標簽
 定義和用法   noscript 元素用來定義在腳本未被執行時的替代內容(文本)。  
 此標簽可被用於可識別 <script> 標簽但無法支持其中的腳本的浏覽器。
 
     注釋:如果浏覽器支持腳本,那麼它不會顯示出 noscript 元素中的文本。
 注釋:無法識別 <script> 標簽的浏覽器會把標簽的內容顯示到頁面上。為了避免浏覽器這樣做,您應當在注釋標簽中隱藏腳本。老式的(無法識別 <script> 標簽的)浏覽器會忽略注釋,這樣就不會把標簽的內容寫到頁面上,而新式的浏覽器則懂得執行這些腳本,即使它們被包圍在注釋標簽中!
21、JavaScript 打字機效果
實例1

<html> 
<title>JavaScript 打字機</title> 
<head> 
<style type="text/css"> 
 body{ 
  font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; 
  margin-top:0px; 
  background-image:url('../../images/heading3.gif'); 
  background-repeat:no-repeat; 
  padding-top:100px; 
 } 
 #myContent, #myContent blink{ 
  width:500px; 
  height:200px; 
  background:black; 
  color: #00FF00; 
  font-family:courier; 
 }  
 blink{ 
  display:inline; 
 
 } 
 </style> 
 <script type="text/javascript"> 
 var charIndex = -1; 
 var stringLength = 0; 
 var inputText; 
 function writeContent(init){ 
  if(init){ 
   inputText = document.getElementById('contentToWrite').innerHTML; 
  } 
  if(charIndex==-1){ 
   charIndex = 0; 
   stringLength = inputText.length; 
  } 
  var initString = document.getElementById('myContent').innerHTML; 
  initStringinitString = initString.replace(/<SPAN.*$/gi,""); 
   
  var theChar = inputText.charAt(charIndex); 
  var nextFourChars = inputText.substr(charIndex,4); 
  if(nextFourChars=='<BR>' || nextFourChars=='<br>'){ 
   theChar = '<BR>'; 
   charIndex+=3; 
  } 
  initStringinitString = initString + theChar + "<SPAN id='blink'>_</SPAN>"; 
  document.getElementById('myContent').innerHTML = initString; 
 
  charIndexcharIndex = charIndex/1 +1; 
  if(charIndex%2==1){ 
    document.getElementById('blink').style.display='none'; 
  }else{ 
    document.getElementById('blink').style.display='inline'; 
  } 
     
  if(charIndex<=stringLength){ 
   setTimeout('writeContent(false)',150); 
  }else{ 
   blinkSpan(); 
  } 
 } 
  
 var currentStyle = 'inline'; 
 function blinkSpan(){ 
  if(currentStyle=='inline'){ 
   currentStyle='none'; 
  }else{ 
   currentStyle='inline'; 
  } 
  document.getElementById('blink').style.display = currentStyle; 
  setTimeout('blinkSpan()',500); 
   
 } 
 </script> 
 
<body> 
 
<div id="myContent"> 
</div> 
<div id="contentToWrite" style="display:none"> 
 <!-- Put the typewriter content here--> 
 sharejs.com 
 Login : username<br> 
 password : ******<br> 
 Access is granted<br> 
 <!-- End typewriter content --> 
 </div> 
 <script type="text/javascript"> 
 writeContent(true); 
</script> 
 
 
</body> 
</html> 

實例2 (兼容IE,FX)

<html> 
<head> 
<title>打字效果的帶鏈接的新聞標題</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<style type="text/css"> 
body{font-size:14px;font-weight:bold;} 
</style> 
</head> 
<body> 
最新內容:<a id="HotNews" href="" target="_blank"></a> 
<script language="JavaScript"> 
var NewsTime = 2000; //每條新聞的停留時間 
var TextTime = 50; //新聞標題文字出現等待時間,越小越快 
 
var newsi = 0; 
var txti = 0; 
var txttimer; 
var newstimer; 
 
var newnewstitle = new Array(); //新聞標題 
var newnewshref = new Array(); //新聞鏈接 
 
newstitle[0] = "javascript常用函數"; 
newshref[0] = "http://www.jb51.net/article/74365.htm"; 
 
newstitle[1] = "http://www.jb51.net/"; 
newshref[1] = "http://www.jb51.net/"; 
 
function shownew() 
{ 
 var endstr = "_"; 
 hwnewstr = newstitle[newsi]; 
 newslink = newshref[newsi]; 
 if(txti==(hwnewstr.length-1)){endstr="";} 
 if(txti>=hwnewstr.length){ 
 clearInterval(txttimer); 
 clearInterval(newstimer); 
 newsi++; 
 if(newsi>=newstitle.length){ 
 newsi = 0 
 } 
 newstimer = setInterval("shownew()",NewsTime); 
 txti = 0; 
 return; 
 } 
 clearInterval(txttimer); 
 document.getElementById("HotNews").href=newslink; 
 document.getElementById("HotNews").innerHTML = hwnewstr.substring(0,txti+1)+endstr; 
 txti++; 
 txttimer = setInterval("shownew()",TextTime); 
} 
shownew(); 
</script> 
</body> 
</html> 

22、簡單打印

<style type="text/css" media=print> 
.noprint{display : none } 
</style> 
 
<input id="btnPrint" type="button" value="打印" onclick="javascript:window.print();" /><br> 
這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,<br> 
這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,<br> 
這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,這裡是被打印的地方,<br> 
<p class="noprint">這裡是不需要打印的地方</p> 

23、禁止右鍵

<html> 
<title>jquery 禁止右鍵</title> 
<head> 
<script src="jquery.js"></script> 
 <script type="text/javascript"> 
 $(function(){ 
  $(document).bind("contextmenu",function(e){ 
   return false; 
  }); 
 }); 
 </script> 
 
<body> 
Xinjiang to implement amended public security measures to safeguard social stability 
Xinjiang to implement amended public security measures to safeguard social stability 
Xinjiang to implement amended public security measures to safeguard social stability 
Xinjiang to implement amended public security measures to safeguard social stability 
Xinjiang to implement amended public security measures to safeguard social stability 
Xinjiang to implement amended public security measures to safeguard social stability 
</body> 
</html> 

24、防止垃圾郵件

<script language="JavaScript"> 
var rJJdg="PYRUq"; 
var vjenFG="@cef.com"; 
var syniH="deo"; // 郵箱名字 
var nQEEGoTp="@Deographics.com"; // 郵箱後綴 
var KnJbiFO="imLCHy"; 
var JTCRe="@GZeejp.com"; 
var NersngGn=2014; // 郵箱地址loading時間 
setTimeout("GRUBeoQUurKVgk()",NersngGn); 
 
function GRUBeoQUurKVgk(){ 
 document.getElementById("TPNTZyRk").href= "mailto:"+syniH + nQEEGoTp; 
 document.getElementById("gTslyYgEq").innerHTML = syniH + nQEEGoTp; 
} 
 
</script> 
<a id=TPNTZyRk><span id="gTslyYgEq">Email Loading...</span></a> 
<span style=display:none;>JwcFoxtWH@aPpeoOw.com RPibMejAUX@NQDg.com PWlVlgKG@QCpBcER.com SxOuqrHes@mszff.com taMmRPLu@EzcI.com NfXidnW@yympz.com quuMcbaKda@aUNdsyb.com DcnXCxaR@QcrN.com QeofXl@ibCh.com OxqzDkSH@hrScW.com</span> 

25、復制(javaeye flash版)

<?php 
 $clipboard = "This is a test !!"; 
?> 
 
<div class="tools"> 
 Javaeye 
 
 <embed tplayername="SWF" 
 splayername="SWF" id="Player1264100331386" type="application/x-shockwave-flash" src="clipboard.swf" 
 mediawrapchecked="true" flashvars="clipboard=<?=$clipboard?>" quality="high" 
 allowscriptaccess="always" 
 pluginspage="http://www.macromedia.com/go/getflashplayer" height="15" width="14"> 
 
 <div><textarea id="blog_content"><?=$clipboard?></textarea></div> 
 
</div> 

26、阻止冒泡事件或阻止浏覽器默認行為

//阻止冒泡事件 
 function stopBubble(e) { 
 if (e && e.stopPropagation) {//非IE 
  e.stopPropagation(); 
 } 
 else {//IE 
  window.event.cancelBubble = true; 
 } 
 } 
 
function stopDefault(e) { 
 //阻止默認浏覽器動作(W3C) 
 if (e && e.preventDefault) 
  e.preventDefault(); 
 //IE中阻止函數器默認動作的方式 
 else 
  window.event.returnValue = false; 
 return false; 
 } 

27、關閉或跳轉窗口時提示

<script language="javascript"> 
 function IsClose() 
 { 
 if(confirm("是否退出系統?")) 
 { 
 return true; 
 } 
 return false; 
 } 
 </script> 
<body onbeforeunload="javascript:if(IsClose()){return false;}else{return true}"> 
 
-------------------------------------------------------- 
</body> 
 
或者
<script> 
function winclose(){ 
 
return '是否退出系統?'; 
} 
</script> 
<body onbeforeunload="return winclose()" > 
 
</body> 

28、用javascript獲取地 址欄參數
//本頁地址為:  alert(document.location);   
方法一:

<script type="text/javascript"> 
<!-- 
String.prototype.getQuery = function(name) { 
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); 
  var r = this.substr(this.indexOf("\?")+1).match(reg); 
  if (r!=null) return unescape(r[2]); return null; 
} 
 
var strHref = "www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc"; 
alert(strHref.getQuery("a")); 
alert(strHref.getQuery("b")); 
alert(strHref.getQuery("c")); 
//--> 
</script> 

 方法二:

<script type="text/javascript"> 
function getUrlPara(paraName){ 
 var sUrl = location.href; 
 var sReg = "(?:\\?|&){1}"+paraName+"=([^&]*)" 
 var re=new RegExp(sReg,"gi"); 
 re.exec(sUrl); 
 return RegExp.$1; 
} 
//應用實例:test_para.html?a=11&b=22&c=33 
alert(getUrlPara("a")); 
alert(getUrlPara("b")); 
</script> 

  
方法三:

<script type="text/javascript"> 
<!-- 
function Request(strName){ 
 var strHref = "www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc"; 
 var intPos = strHref.indexOf("?"); 
 var strRight = strHref.substr(intPos + 1); 
 var arrTmp = strRight.split("&"); 
 
 for(var i = 0; i < arrTmp.length; i++) { 
 var arrTemp = arrTmp[i].split("="); 
 if(arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTemp[1]; 
 } 
 return ""; 
} 
alert(Request("a")); 
alert(Request("b")); 
alert(Request("c")); 
//--> 
</script> 

 29、計算停留的時間

<html> 
<form name="myform"> 
<td vAlign="top" width="135">您在此停留了: 
<input name="clock" size="8" value="在線時間"></td> 
</form> 
<script language="JavaScript"> 
var id, iM = 0, iS = 1; 
start = new Date(); 
function go(){ 
 now = new Date(); 
 time = (now.getTime() - start.getTime()) / 1000; 
 time = Math.floor( time); 
 iS = time % 60; 
 iM = Math.floor( time / 60); 
 if ( iS < 10) 
 document.myform.clock.value = " " + iM + " 分 0" + iS + " 秒"; 
 else 
 document.myform.clock.value = " " + iM + " 分 " + iS + " 秒"; 
 id = setTimeout( "go()", 1000); 
} 
go(); 
</script> 
</body> 
</html> 

30、div為空,只有背景時,背景自動增高

<script src="jquery-latest.js"></script> 
<script> 
 $(function(){ 
 var $height = $('#main').height(); // main 是主體自動增高的 id 
 $('#bg').css('height',$height); // bg 是隨主體自動增高的無內容背景div的id,一般是陰影之類的 
 }) 
</script> 

 

iframe 版

<iframe src="iframe_b.html" scrolling="no" frameborder="0" width="100%" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe> 

以上就是小編為大家整理的常用的javascript函數,希望對大家的學習有所幫助,還有最後一篇關於常用的javascript函數的文章即將推出,繼續關注。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved