总结 input propertychange 监听输入框

时间:2022-08-23 10:03:17
常常会有输入框检查的需求,最常见的就是即时搜索。
即时搜索的三个方案:
(1) change事件—触发该事件必须满足两个条件:
  1. 当前对象属性改变,并且是由键盘或鼠标事件激发的(脚步触发无效)
  2. 当前对象失去焦点(onblur)
(2) keypress 就是只能监听键盘事件,鼠标复制粘贴操作无能为力
(3) propertychange(ie) 和 input 事件
  1. input 是标准的浏览器事件,一般应用于input元素,当 input 的 value 发生变化就会触发,无论是键盘输入还是鼠标粘贴的改变都能及时监听到变化。
  2. propertychange 只要当前对象属性发生改变就会触发。(IE专属的)
目前 input & propertychange 仍然是即时搜索比较好的解决方案。
补充 MDN 上对 input event 的描述:
The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed. (For input elements with type=checkbox or type=radio, the input event does not fire when a user clicks the control, because the value attribute does not change.) Additionally, it fires on contenteditable editors when its contents are changed. In this case, the event target is the editing host element. If there are two or more elements which have contenteditable as true, "editing host" is the nearest ancestor element whose parent isn't editable. Similarly, it's also fired on root element of designMode editors.