前言
在作web開發時候不少時候都須要即時監聽輸入框值的變化,以便做出即時動做去引導瀏覽者加強網站的用戶體驗感。而採用onchange時間又每每是在輸入框失去焦點(onblur)時候觸發,有時候並不能知足條件。javascript
首先看一下dom中元素事件:java
onpropertychange: IE下,當一個HTML元素的屬性改變的時候,都能經過 onpropertychange來即時捕獲。onchange在屬性值改變時還必須使得當前元素失去焦點(onblur)才能夠激活該事件。 在用js腳本改動該元素值時候亦能觸發onpropertychange事件。
oninput:是onpropertychange的非IE瀏覽器版本,支持firefox和opera等瀏覽器,但有一點不一樣,它綁定於對象時,並不是該對象全部屬性改變都能觸發事件,它只在對象value值發生改變時奏效。
onchange: (a)當前對象屬性改變,而且是由鍵盤或鼠標事件激發的(腳本觸發無效);(b)當前對象失去焦點(onblur);
jQuery用法
$("#input1").bind("input propertychange",function(event){
console.log($("#input1").val())
});
原生Js
<script type="text/javascript">
// Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
function OnInput (event) {
alert ("The new content: " + event.target.value);
}
// Internet Explorer
function OnPropChanged (event) {
if (event.propertyName.toLowerCase () == "value") {
alert ("The new content: " + event.srcElement.value);
}
}
</script>
//Input標籤
<input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />
web
項目中遇到一個問題:在input上加了一個監聽事件瀏覽器
$('#inputId').bind('input propertychange', function() {
dosomethig...
});dom
但我在使用Js改變這個input的值後,監聽事件並不能觸發網站
緣由:firefox
使用Js動態改變input的值時,沒有任何鼠標和鍵盤的事件,因此並不能觸發監聽對象
解決:事件
在Js改變這個值以前加上一句話:$("#inputId").trigger("input"); 問題得以解決
ip