关于textarea的应用--onchage,onpropertychange,oninput

 oninput,onpropertychange,onchange的用法

1、onchange触发事件必须满足两个条件:

a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效)

b)当前对象失去焦点(onblur);

2、onpropertychange的话,只要当前对象属性发生改变,都会触发事件,但是它是IE专属的;

3、oninput是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。

在textarea中,如果想捕获用户的键盘输入,用onkeyup检查事件就可以了,但是onkeyup并不支持复制和粘贴,因此需要动态监测textarea中值的变化,这就需要onpropertychange(用在IE浏览器)和oninput(非IE浏览器)结合在一起使用了。

 好吧让我们来做个例子吧:

经常在SNS中看到如下图所示的功能:

T17wqkFXtXXXcDECcS-547-180

请通过代码完成它,它至少应该:
1. 良好结构、语义化的HTML
2. 兼容主流的浏览器;
3. JS应该包括: 1) 实时计数功能 2)校验字数限制 3) 防止重复提交;

解答:

<form id="form1" action="" method="post">
			<div class="numbox"><b id="num"></b>/1500</div>
			<textarea id="message" maxlength=1500 style="200px;height:100px">1500字以内</textarea>
			<input type="submit" name="submit" id="ok">发布</input>
		</form>
		<script>
			var form=document.getElementById('form1');
			var button=document.getElementById('ok');
			var textbox=document.getElementById('message');
			var num=document.getElementById('num');
			var empty=true;
			textbox.onfocus=function(){
				if(textbox.value=="1500字以内"){
					textbox.value="";
				}
			}
			textbox.onblur=function(){
				if(textbox.value==""){
					empty=true;
					textbox.value="1500字以内";
				}else{
					empty=false;
				}
			}
			function hander(){
				num.innerHTML=textbox.value.length;
			}
			if(window.ActiveXObject){
				textbox.onpropertychage=hander;
			}else{
				textbox.addEventListener("input",hander,false);
			}

			form.onsubmit=function(){
				button.disabled=true;
			}

		</script>

  

原文地址:https://www.cnblogs.com/dunken/p/4361946.html