收获:用!-[1,]能判断是否ie
字节数:用两个英文字母去替换一个汉字然后再去算长度
<style type="text/css">
.anot{color:gray}
.acan{red;}
</style>
<script type="text/javascript">
var ie = !-[1,];//检测ie678
var num = 140;
window.onload = function(){
var oT = document.getElementsByTagName('textarea')[0];
var oP = document.getElementsByTagName('p')[0];
var oA = document.getElementsByTagName('a')[0];
oT.onfocus = function(){
oP.innerHTML='您还可以输入<span>140<span> 字';
}
oT.onblur = function(){
oP.innerHTML='新浪微博';
}
if(ie){
oT.onpropertychange = tips;
}
else{
oT.oninput = tips;
}
function tips(){
var str = oT.value;
num = Math.ceil(len(str)/2);
var oSpan = document.getElementsByTagName('span')[0];
if(!oSpan) return ;
if(num<=140){
oSpan.innerHTML = 140-num;
}
else{
oSpan.innerHTML = 140-num;
oSpan.style.color='red';
}
if(str=='' || num>140){
oA.className='anot'
}
else{
oA.className='acan';
}
}
function len(str){
return String(str).replace(/[^\x00-\xff]/g,'aa').length;//汉字子用英文字母aa的长度代替
}
};
</script>
</head>
<body>
<div id="div1">
<p>新浪微博<p>
<textarea cols="40" rows="10"></textarea>
<a href="void(0);" class="anot">发布</a>
</div>
</body>
</html>
转载于:https://blog.51cto.com/zhangshibiao/1171772