編程(Programming)是編定程序的中文簡稱,就是讓計算機代碼解決某個問題,對某個計算體系規定一定的運算方式,使計算體系按照該計算方式運行,并最終得到相應結果的過程。為了使計算機能夠理解(understand)人的意圖,人類就必須將需解決的問題的思路、方法和手段通過計算機能夠理解的形式告訴計算機,使得計算機能夠根據人的指令一步一步去工作,完成某種特定的任務。這種人和計算體系之間交流的過程就是編程。 【實例名稱】 JS編寫表單驗證樣式 【實例描述】 實現表單驗證的樣式有很多,本例將使用一種類似AjaX效果的驗證方法實現一個分數(數值型)的驗證。 【實例代碼】 <html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Check Score-本站(www.xue51.com)</title>
<style type="text/css">
#name div.text{
float:left;
width:118px;
font-size:12px;
text-align:right;
font-weight:bold;
}
#name div.redstar {
float:right;
width:10px;
font-size:12px;
text-align:right;
font-weight:normal;
color:#ff0000;
margin-right:3px;
}
div.input{
width:257px;
text-align:left;
float:left;
font-size:12px;
}
div.note{
width:310px;
float:right;
text-align:left;
font-size:12px;
color:#999999;
padding:3px;
line-height:130%;
background:#ffffff;
border:#ffffff 1px solid;
}
div.notetrue{
width:310px;
float:right;
text-align:left;
font-size:12px;
padding:3px;
line-height:130%;
color:#485E00;
background:#F7FFDD;
border:#485E00 1px solid;
}
div.noteawoke{
display: none;
width:310px;
float:right;
text-align:left;
font-size:12px;
color:#ff0000;
padding:3px;
line-height:130%;
background:#fff5d8;
border:#ff7300 1px solid;
background-repeat:no-repeat;
background-position:2 3px;
margin:0px;
}
</style>
</head>
<body>
<table>
<tr>
<td id="name"><div class="text">得分</div>
<div class="redstar">*</div></td>
<td><div class="input">
<input type="text" id="txtScore" /><div></td>
<td><div class="note" id="divTipInfo">
請輸入 0-100 之間的數字!</div>
<div class="noteawoke" id="divAlarmInfo">
數據輸入錯誤,重新輸入!</div></td>
</tr>
</table>
<script type="text/javascript">
var oScore = document.getElementById("txtScore");
//獲取輸入文本框
var oNote = document.getElementById("divTipInfo");
//獲取提示信息框
var oAlarm = document.getElementById("divAlarmInfo");
//獲取警告信息框
oScore.onfocus = function()
{
oNote.className = "notetrue";
//獲取焦點時改變樣式
}
oScore.onblur = function()
//失去焦點時的方法
{
if (this.value != "")
{
var score = parseInt(this.value);
//轉換數值類型
//判斷輸入內容是否符合條件
if (isNaN(score) || !(score>=0 && score<=100))
{
oAlarm.style.display = "block";
oNote.style.display = "none";
}
else
{
this.value = score;
oAlarm.style.display = "none";
oNote.className = "note";
oNote.style.display = "block";
}
}
else
{
//用戶沒有輸入的情況下
oAlarm.style.display = "none";
oNote.className = "note";
oNote.style.display = "block";
}
}
</script>
</body>
</html>
【運行效果】  【難點剖析】 本例的重點是輸入框的兩個事件:“onfocus”和“onblur”。當輸入框獲得焦點時,改變提示框的樣式,如果用戶輸入錯誤則顯示警告信息框,隱藏提示框。本例中CSS樣式表起到了很大的作用。 【源碼下載】 為了JS代碼的準確性,請點擊:JS編寫表單驗證樣式 進行本實例源碼下載
使用編程語言寫的程序,由于每條指令都對應計算機一個特定的基本動作,所以程序占用內存少、執行效率高。 |