<script type="text/javascript">
window.onload = function () {
var oDiv = document.getElementById('div1');
var op = oDiv.getElementsByTagName('p')[0];
var oT = oDiv.getElementsByTagName('textarea')[0];
var oA = oDiv.getElementsByTagName('input')[0];
var oBtn = true;
//var ie = ! -[1, ]; //判断是否是ie -[1,]为NaN 即false --ie9+不适合
var timer;
var iNum = 0;
oT.onfocus = function () {
if (oBtn) {
op.innerHTML = '你还可以输入<span>100</span>字';
oBtn = false;
}
}
oT.onblur = function () {
if (oT.value == '') {
op.innerHTML = '1234567';
oBtn = true;
}
}
if (window.navigator.userAgent.indexOf("MSIE") >= 0) {
oT.onpropertychange = tochange; //ie
} else {
oT.oninput = tochange;
}
//文本改变调用函数
function tochange() {
var num = Math.ceil(getLength(oT.value) / 2);
var oSpan = oDiv.getElementsByTagName('span')[0];
if (oSpan) {
if (num < 100) {
oSpan.innerHTML = 100 - num;
oSpan.style.color = '';
} else {
oSpan.innerHTML = num - 100;
oSpan.style.color = 'red';
}
}
}
//获取文本长度 字母,半角数字每两个算是一个字
function getLength(str) {
return String(str).replace(/[^\x00-\xff]/g, 'aa').length;//将每个全角和汉字转换成两个字节的字母
}
oA.onclick = function () {
if (oT.value == '' || oT.value.length > 100) {
clearInterval(timer); //防止用户一直点击
//超出文本范围或者未填写 文本框样式
timer = setInterval(function () {
if (iNum == 5) {
clearInterval(timer);
iNum = 0;
} else {
iNum++;
}
if (iNum % 2) { //为1
oT.style.background = 'red';
} else {
oT.style.background = '';
}
}, 100);
} else {
alert('ok');
}
}
}
</script>
<div id="div1">
<p>1234567</p>
<textarea></textarea>
<input type="button" value="测试" />
</div>