知识点
运行效果
初始:
输入0-100:
输入错误:
每一次重新获得焦点样式都会重置
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#prompt{
font-size: 13px;
color:darkgrey;
}
#score{
border: 1px solid darkgrey;
}
.right{
background: url("正确.png") no-repeat 5px center ;
background-size: 15px 15px;
padding-left: 20px;
color: #29ff16 !important;
}
.error{
background: url("错误 (1).png") no-repeat 5px center ;
background-size: 15px 15px;
padding-left: 23px;
color: red !important;
}
</style>
</head>
<body>
<div id="box">
<label>您的成绩:</label>
<input type="text" placeholder="请输入成绩" id="score">
<span id="prompt">请输入您的成绩!</span>
</div>
</body>
<script src="MyTools.js"></script>
<script>
window.addEventListener('load',function () {
var score = myTool.$('score');
var prompt = myTool.$('prompt');
// 当输入框失去焦点
score.addEventListener('blur',function () {
// 1. 获取输入内容 转为number
var value = parseFloat(score.value);
// 2. 验证
if (isNaN(value)){ // 不是一个数
dealStyle('输入成绩不正确!', 'error', 'red');
}else if(value>= 0 && value<= 100){ //合法的
dealStyle('输入成绩正确!', 'right', '#29ff16');
}else{
dealStyle('请输入0-100的数字!', 'error', 'red');
}
});
// 当输入框获得焦点
score.addEventListener('focus',function () {
score.style.outline = 'none';
score.value = '';
dealStyle('请输入您的成绩', '', 'darkgrey');
});
/**
* 处理公共样式
* @param {string}msg
* @param {string}className
* @param {string}color
*/
function dealStyle(msg, className, color) {
prompt.innerText = msg;
prompt.className = className;
score.style.borderColor = color;
}
});
</script>
</html>
来源:CSDN
作者:KaiSarH
链接:https://blog.csdn.net/KaiSarH/article/details/103773670