一、描述
我们在空间中发表状态,当我们输入一个字符,上面的剩余可输入字符数就会减一,直到输入的字符数达到之前设定的最大数量为止,效果如下图所示:
二、实现方法
首先,我们先确定文本框内的最大可输入长度,其次在输入一个字符抬起键盘的时候对输入文本框中的字符长度进行验证,并在动态显示在剩余可输入字符数中。
三、源代码
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%><%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!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=utf-8" />
<title>版块</title><style type="text/css">
.pbt {margin-bottom: 10px;
}
.ie6 .pbt .ftid a, .ie7 .pbt .ftid a {margin-top: 1px;
}
.cl:after {clear: both;content: ".";display: block;height: 0;visibility: hidden;
}
</style>
<script type="text/javascript"> //光标离开这个textField就验证该文本框是否为空function check(){ var forumPost = document.getElementById("subject");var forumPostName = forumPost.value;var subjectchkRule = document.getElementById("subjectchk");var postNameRule = document.getElementById("postNameRule");postNameRule.style.color="#FF0000";if(forumPostName == ""){subjectchkRule.style.display="none";postNameRule.style.display="none";postNameRule.innerHTML="*帖子标题不能为空";forumPost.focus(); }else{postNameRule.innerHTML="";} }// 只要键盘一抬起就验证编辑框中的文字长度,最大字符长度可以根据需要设定function checkLength(obj) { var maxChars = 80;//最多字符数 var curr = maxChars - obj.value.length; if( curr > 0 ){document.getElementById("checklen").innerHTML = curr.toString(); }else{document.getElementById("checklen").innerHTML = '0';document.getElementById("subject").readOnly=true;}} </script>
</head>
<body><div class="pbt cl"> <s:textfield name="mcpForumPost.postTitle" id="subject" size="80" maxlength="80" theme="simple" οnblur="check()" οnkeyup="checkLength(this)" accessKey="1" tabindex="11"></s:textfield><span id="subjectchk">还可输入<strong id="checklen" style="color:#FF0000">80</strong>个字符</span><span id="postNameRule" class="spn_flag_1" style="display:none" ></span></div>
</body>
</html>