DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 獲取焦點時,利用js定時器設定時間執行動作
獲取焦點時,利用js定時器設定時間執行動作
編輯:關於JavaScript     
進入正題,先說說定時器。
在javascritp中,有兩個關於定時器的專用函數,分別為:
1.倒計定時器:timename=setTimeout("function();",delaytime);
2.循環定時器:timename=setInterval("function();",delaytime);
第一個參數“function()”是定時器觸發時要執行的動作,可以是一個函數,也可以是幾個函數,函數間用“;”隔開即可。比如要彈出兩個警告窗口,便可將“function();”換成
“alert('第一個警告窗口!');alert('第二個警告窗口!');”;而第二個參數“delaytime”則是間隔的時間,以毫秒為單位,即填寫“5000”,就表示5秒鐘。
  倒計時定時器是在指定時間到達後觸發事件,而循環定時器就是在間隔時間到來時反復觸發事件,兩者的區別在於:前者只是作用一次,而後者則不停地作用。
比如你打開一個頁面後,想間隔幾秒自動跳轉到另一個頁面,則你就需要采用倒計定時器“setTimeout("function();",delaytime)” ,而如果想將某一句話設置成一個一個字的出現,
則需要用到循環定時器“setInterval("function();",delaytime)” 。

獲取表單的焦點,則用到document.activeElement.id。利用if來判斷document.activeElement.id和表單的ID是否相同。
比如:if ("mid" == document.activeElement.id) {alert();},"mid"便是表單對應的ID。

一下略舉兩例。
例1.表單觸發或加載時,逐字輸出字符串
復制代碼 代碼如下:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script language="JavaScript" type="text/javascript">
var str = "這個是測試用的范例文字";
var seq = 0;
var second=1000; //間隔時間1秒鐘
function scroll() {
msg = str.substring(0, seq+1);
document.getElementById('word').innerHTML = msg;
seq++;
if (seq >= str.length) seq = 0;
}
</script>
</head>
<body onload="setInterval('scroll()',second)">
<div id="word"></div><br/><br/>
</body>
</html>


例2.當焦點在輸入框的時候,定時檢查輸入框信息,焦點不在時不執行檢查動作。
復制代碼 代碼如下:
<!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=gb2312" />
<title>無標題文檔</title>
<script language="JavaScript" type="text/javascript">
var second=5000; //間隔時間5秒鐘
var c=0;
function scroll() {
c++;
if ("b" == document.activeElement.id) {
var str="定時檢查第<b> "+c+" </b>次<br/>";
if(document.getElementById('b').value!=""){
str+="輸入框當前內容為當前內容為<br/><b> "+document.getElementById('b').value+"</b>";
}
document.getElementById('word').innerHTML = str;
}
}
</script>
</head>
<body>
<textarea id="b" name="b" style="height:100px; width:300px;" onfocus="setInterval('scroll()',second)"></textarea><br/><br/>
<div id="word"></div><br/><br/>
</body>
</html>


例3.下面這個是最簡單的例子,定時器時間到達後彈出警告窗口。
復制代碼 代碼如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script language="javascript">
function count() {
document.getElementById('m').innerHTML="計時已經開始!";
setTimeout("alert('十秒鐘到!')",10000)
}
</script>
<body>
<div id="m"></div>
<input TYPE="button" value=" 計時開始" onclick="count()">
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved