JS限制输入[转载]
JS:
function checkWord(len){
var src=window.event.srcElement;
var str=trim(src.value);
myLen=0;
i=0;
for(;(i<str.length)&&(myLen<=len);i++){
if(str.charCodeAt(i)>0&&str.charCodeAt(i)<128)
myLen++;
else
myLen+=2;
}
//var myLen=str.replace(/[^\x00-\xff]/g,"**").length;
var mydiv=document.getElementById("wordCheck");
if(myLen>len){
alert("\u60a8\u8f93\u5165\u7684\u5b57\u6570\u8fc7\u591a\uff0c\u8bf7\u91cd\u65b0\u8f93\u5165");
src.value=str.substring(0,i-1);
window.frames.wordFrame.document.write("<body style='margin-bottom:0px; margin-left:5px; margin-right:0px; margin-top:6px;'> <span style='font-family:??, Verdana, Lucida, Arial, Helvetica,sans-serif;font-size:14px;color:#036;'>\u60a8\u8fd8\u53ef\u4ee5\u8f93\u51650\u4e2a\u5b57\u7b26</span></body>");
window.frames.wordFrame.document.close();
}
else{
window.frames.wordFrame.document.write("<body style='margin-bottom:0px; margin-left:5px; margin-right:0px; margin-top:6px;'> <span style='font-family:\u5b8b\u4f53, Verdana, Lucida, Arial, Helvetica,sans-serif;font-size:14px;color:#036;'>\u60a8\u8fd8\u53ef\u4ee5\u8f93\u5165"+(len-myLen)+"\u4e2a\u5b57\u7b26</span></body>");
window.frames.wordFrame.document.close();
}
mydiv.style.visibility="visible";
var myx=0,myy=0;
var parent = src.offsetParent
while(parent){
myx += parent.offsetLeft;
myy += parent.offsetTop;
parent=parent.offsetParent;
}
mydiv.style.left=myx+5;
mydiv.style.top=myy-25;
}
function hiddWordDiv(){
document.getElementById("wordCheck").style.visibility="hidden";
}
HTML:
<script type="text/javascript" src="checkWord.js"></script>
……
<div style="position:absolute; width:155px;height=28px;z-index:100;border:#4298E1 solid 1px; background-color:#fff; visibility:hidden; FILTER: Alpha(opacity=85)" id="wordCheck">
<iframe name="wordFrame" frameborder="0" id="wordFrame" style="width:155px; height:28px;z-index:101;" scrolling="no">
</iframe>
</div>
<input type="text" size="70" maxlength="80" name="giftDescribe" onkeyup="javascript:checkWord(80)" onblur="javascript:hiddWordDiv()">
作者:Olar Tan
出处:http://www.cnblogs.com/olartan
♪:没有做不到的 只有偷懒而错过的 ♪