<!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" />
<meta http-equiv="content-language" content="zh-CN" />
<title> new document </title>
</head>

<body>
<div id="wrapper">
<textarea id="content" maxlength="10" rows="5"></textarea>
<div id="content-tip"></div>
</div>
<script language="JavaScript">
<!--
(function() {
var id = function(s) {return document.getElementById(s);}
var addEvent = function(o, t, f) {
 o['on'+t] = f;
}
var css = function(o, r) {
 var style = o.style;
 for (var i in r) {
  style[i] = r[i];
 }
}
var attribute = function(o, k, v) {
 if (o && o.getAttribute) {
  if (v) o.setAttribute(k, v);
  else return o.getAttribute(k);
 } else {
  if (v) o[k] = v;
  else return o[k];
 }
}

var eventObject = function(e) {
 return e || window.event;
}

var keyCode = function (e) {
 return e.keyCode || e.charCode;
}

var VK_BACKSPACE = 8;
window.counterTimers = {};

function attachCounter() {
 var self = this;
 var maxlength = parseInt(attribute(self, "maxlength"));

 var tip = id(this.id + "-tip");
 if (maxlength && maxlength > 0) {
  window.counterTimers[this.id] = setInterval(function() {
   var cur = self.value.length;
   var remainder  = maxlength - cur;
   if (remainder > 0) {
    tip[tip.innerText !== undefined ? "innerText" : "textContent"]  = "当前还可以输入的字数:" + remainder;
    css(tip, {"color":"green"});
    self.onkeypress = function(e) {};
   } else {
    //var cut = self.value.substring(maxlength+1); //取超出的内容
    //self.value = self.value.substring(0, maxlength); //截取
    tip[tip.innerText !== undefined ? "innerText" : "textContent"] = "当前输入内容长度已经超出 " + -remainder + " 字,不能再输入了,请删除,否则系统自动截取,会丢失数据!";
    css(tip, {"color":"red"});
    self.onkeypress = function(e) { //防止继续输入
     var k = keyCode(eventObject(e));
     if (VK_BACKSPACE !== k) return false;
    }
   }
   
  }, 500);
 }
}
function detachCounter() {
 if(window.counterTimers[this.id]) {
  clearInterval(window.counterTimers[this.id]);
 }
}

addEvent(id('content'), 'focus', attachCounter);
addEvent(id('content'), 'blur', detachCounter);
})();
//-->
</script>
</body>
</html>

posted on 2010-01-16 15:32  sweting  阅读(288)  评论(0编辑  收藏  举报