1、在登錄、注冊時,我們經常會遇到下面這種情況,如果我們沒有輸入用戶名、密碼時,系統會彈出提示框。提示框信息提示內容是我們密碼沒有輸入密碼或者用戶名等。那么這樣的彈出框效果是如何實現的呢?文章標題既然與js有關,那么我們就用js來實現這個功能,當然實現此功能的還有其他方法,在這里我用js去實現。
2、用表格布局先布局一個簡單的html表單頁面:
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js驗證表(是否輸入單用戶名、密碼)</title>
<style type="text/css"> *{padding: 0;margin: 0} table{margin:0 auto;margin-top: 200px}
</style>
</head>
<body>
<form name="form1" method="post" action=""><!--這里用js實現跳轉-->
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td height="50" colspan="2" bgcolor="#eeeeee" align="center">用戶登錄</td>
</tr>
<tr>
<td width="70" height="50">用戶名:</td>
<td><input name="user" type="text" id="user" maxlength="8"><!--8指的是8個漢字,8個字符--></td>
</tr>
<tr>
<td width="70" height="50">密 碼:</td>
<td><input name="pwd" type="password" id="pwd" maxlength="16"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input name="reset" type="reset" value="重置">
<input name="button" type="button" value="登錄" onclick="check()">
</td>
</tr>
</table>
</form>
<script language="JavaScript" type="text/javascript" src="demo.js"></script>
</body>
</html>
html頁面效果圖:
然后新建js文件:demo.js,代碼如下:
function check() {
var user_name=form1.user.value;//獲取表單form1的用戶名的值
var user_pwd=form1.pwd.value;//獲取表單form1密碼值
if((user_name=="")||(user_name==null)){//判斷用戶名是否為空,為空就彈出提示框"請輸入用戶名",否則正常執行下面的代碼。
alert("請輸入用戶名!");
form1.user.focus();//獲取焦點,即:鼠標自動定位到用戶名輸入框,等待用戶輸入用戶名。
return;
}
else if((user_pwd=="")||(user_pwd==null)){//判斷密碼是否為空,為空就彈出提示框"請輸入密碼",否則正常執行下面的代碼。
alert("請輸入密碼!");
form1.pwd.focus();//獲取焦點。
return;}
else {//如果用戶名、密碼都正常輸入,則提交表單,瀏覽器經打開新的(主頁)窗口。
form1.submit();
// window.location.href="http://baidu.com/";
window.open("http://www.cnblogs.com/qikeyishu/");
}
}
效果圖:
分析:在這里我們運用了常見的if判斷語句只需對用戶名、密碼設定不能為null(空)進行判定,即可實現此功能。