一些表单中的输入框输入之后会进行判断,会在input框之后以√×来表示判断的结果,下面我使用伪元素来简单的实现这个功能。代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用伪元素简单实现input框后的√×</title>
<script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.js"></script>
<style type="text/css">
body {
font-family: "微软雅黑";
font-size: 20px;
color: #000;
}
label {
height: 24px;line-height: 24px;
}
input {
height: 24px;line-height: 24px;
}
.true:after {
display: inline-block;
content: '√';
width: 20px;
height: 20px;
vertical-align: middle;
line-height: 24px;
color: green;
}
.false:after {
display: inline-block;
content: '×';
width: 20px;
height: 20px;
vertical-align: middle;
line-height: 24px;
color: green;
}
</style>
</head>
<body>
<label id="inputBox"><input type="text" name="user" id="input"></label>
<script>
$("#input").blur(function(){
if($(this).val() == "对"){
$("#inputBox").removeClass("false").addClass("true");
}else if($(this).val() == "错"){
$("#inputBox").removeClass("true").addClass("false");
}
});
</script>
</body>
</html>
使用js或者jQuery好像获取不到伪元素,我试了几种方法都显示undefined,至于原因我看网上说的是伪元素不是Dom节点,所以是获取不到的。(我用的jQuery版本是1.11.3,其他版本没有试)。
最后是采用加减class类名来实现的,将两个状态下的伪元素绑定在两个类名之后,在不同的判断结果时候只需要添加或删除相应的class类名即可。