Example:
Copy codeThe Code is as follows:
<! 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> JS Verification Code </title>
<Style type = "text/css">
. Code
{
Background-image: url(code.jpg );
Font-family: Arial;
Font-style: italic;
Color: Red;
Border: 0;
Padding: 2px 3px;
Letter-spacing: 3px;
Font-weight: bolder;
}
. Unchanged
{
Border: 0;
}
</Style>
<Script language = "javascript" type = "text/javascript">
Var code; // define the verification code globally
Function createCode ()
{
Code = "";
Var codeLength = 4; // The length of the Verification Code
Var checkCode = document. getElementById ("checkCode ");
Var selectChar = new Array (,); // All characters of the verification code that can be composed of candidates.
For (var I = 0; I <codeLength; I ++)
{
Var charIndex = Math. floor (Math. random () * 10 );
Code + = selectChar [charIndex];
}
// Alert (code );
If (checkCode)
{
CheckCode. className = "code ";
CheckCode. value = code;
}
}
Function validate ()
{
Var inputCode = document. getElementById ("input1"). value;
If (inputCode. length <= 0)
{
Alert ("Enter the verification code! ");
}
Else if (inputCode! = Code)
{
Alert ("Incorrect verification code! ");
CreateCode (); // refresh the verification code
}
Else
{
Alert ("OK ");
}
}
</Script>
</Head>
<Body onload = "createCode ()">
<Form action = "#">
<Input type = "text" id = "input1"/>
<Input type = "text" onclick = "createCode ()" readonly = "readonly" id = "checkCode" class = "unchanged" style = "width: 80px "/> <br/>
<Input id = "Button1" onclick = "validate ();" type = "button" value = "OK"/>
</Form>
</Body>
</Html>