js監聽input輸入框值的實時變化

*注:(1)&(2)爲其餘文章的說明~javascript

一、在元素上同時綁定 oninput 和onporpertychanger事件
例:css

<script type="text/JavaScript">
function aa(e){alert("inputting!!");}
</script>

<input type="text" id="a" oninput="aa(event)" onporpertychange="aa(event)" />

二、使用原生js添加監聽事件html

<script type="text/javascript">
 $(function(){
if("\v"=="v"){//true爲IE瀏覽器,感興趣的同窗能夠去搜下,聽說是現有最流行的判斷瀏覽器的方法
document.getElementById("a").attachEvent("onporpertychange",function(e){
console.log("inputting!!");
}
}else{
document.getElementById("a").addEventListener("onporpertychange",function(e){
console.log("inputting!!");
}
}
});
</script>
<input type="text" id="a"/>

三、使用jQuery方法綁定事件java

<script type="text/javascript">
 $(function(){
$("#a").bind('input porpertychange',function(){
console.log("e");
});
});
</script>
<input type="text" id="a"/>

在監聽到 onpropertychange 事件後,能夠使用 event 的 propertyName 屬性來獲取發生變化的屬性名稱,event.propertyName瀏覽器

實例1:字體

<input type="text" oninput=" " onpropertychange=""  value="Text field" />

實例2:this

$("#name").bind('input porpertychange',function(){
        var thisTxt=$("#name").val();
        $(this).siblings("p").html(thisTxt)
    })

實例3:code

//手機號碼分段顯示
register.phonePropertychange = function() {
    _this = register;
    _input = $(this);
    var v = $(this).val();
    v = v.replace(new RegExp(/ /g),'');
    var v1 = v.slice(0,3);
    var v2 = v.slice(3,7);
    var v3 = v.slice(7,11);
    if(v2==''){
        _input.focus().val(v1);
    }else if(v3==''){
        _input.focus().val(v1+' '+v2);
    }else{
        _input.focus().val(v1+' '+v2+ ' '+v3);
    };
 
    //手機號輸入完成字體顏色改變
    if (v.length === 11) {
        if(_this.regexpPhone(v)){
            _input.css('color','#000');
            $('#btnSendCode').addClass('c-26a949');
            _input.blur();;
        }else{
            layer.open({content: '手機號碼不正確,請從新輸入',time: 2, end:function(){
                _input.val('');
            }});
        }
    }else{
        _input.css('color','#26a949');
    }
}

//驗證手機號
register.regexpPhone = function(phone){
    return /^1[3|4|5|7|8]\d{9}$/.test(phone);
}
相關文章
相關標籤/搜索