用JavaScript实现文字验证
开发工具与关键技术:JavaScript
作者:陈希雄
撰写时间:2019/2/26
<head>
<meta name="viewport" content="width=device-width" />
<title>ddasa</title>
<style>
#div1 i{
margin-left:5%
}
</style>
</head>
<body>
<div>
<div style="text-align:center;width: 400px;margin-left: 20%;margin-top: 6%;">
<div id="div1" style="background-image: url('../../../../Content/壁纸包/362092.jpg');width: 430px;line-height: 120px;text-align:center;font-size:37px;font-weight:bolder;margin-bottom:3%" >
</div>
<span id="div2" style="font-size:20px"></span> <span style="font-size:20px;color:red;background-color:bisque;cursor:pointer" onclick="fromCharCodetext()">看不清,点击一下这里</span>
<br />
<br />
<input type="button" style="font-size:20px" value="验 证" onclick="dasda()" />
</div>
</div>
<script>
var ss;
var sss;
fromCharCodetext();
function fromCharCodetext() {
ss = "";
sss = "";
var s1 = 20000;
var ys = 143;
var length = document.getElementById("div1");
if (length.children.length > 0) {
for (var y = 0; y < length.children.length; y++)
{
length.removeChild(length.childNodes[1]);//删除子元素
y--;
}
}
var array = new Array('①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩');
for (var i = 0; i < parseInt(Math.random() * 4) + 2 ; i++) {//随机数 parseInt(Math.random() * 5)
var z = String.fromCharCode(s1 + parseInt(Math.random() * 1000));//fromCharCode 从字符编码创建一个字符串。
if (i < parseInt(Math.random() * 3) + 2)
{
ss += z;
}
var s = document.createElement("i");//创建i标签
// var vs = document.createElement("i");//创建i标签
s.style = "color:#" + parseInt(Math.random() * 500) + ys + ""//随机颜色
var i2 = document.createTextNode("" + z + "");//随机汉字
s.appendChild(i2);
var q = 0;
document.getElementById("div1").appendChild(s);
s.onclick = function () {
if (/①|②|③|④|⑤|⑥|⑦|⑧|⑨|⑩/.test(this.textContent)) {
q--;
this.textContent = this.textContent.replace(array[q], "");
sss = sss.replace(this.textContent, "");
} else {
sss += this.textContent;
var i2 = document.createElement("span");//随机汉字
i2.style = "color:blue;font-size:21px";
i2.appendChild(document.createTextNode("" + array[q] + ""))
this.appendChild(i2);
q++;
}
}
}
if (parseInt(Math.random() * 2) == 1)
{
var str= ss.split("").reverse().join("");//字符串反转
document.getElementById("div2").innerHTML=str;
} else {
document.getElementById("div2").innerHTML = ss;
}
}
function dasda() {
if (document.getElementById("div2").innerHTML == sss) {
alert("验证成功");
fromCharCodetext()
} else {
alert("验证失败")
fromCharCodetext()
}
}
</script>
效果: