且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使输入字段中的某些文本不可编辑?

更新时间:2023-01-24 17:12:37

hacky解决方案,但使用JS可以解决问题.

A hacky solution, but kinda does the trick using JS.

<input id="myId" type="text" value="AZ"></input>

$("#myId").keydown(function(event){
    console.log(this.selectionStart);
    console.log(event);
    if(event.keyCode == 8){
        this.selectionStart--;
    }
    if(this.selectionStart < 2){
        this.selectionStart = 2;
        console.log(this.selectionStart);
        event.preventDefault();
    }
});

$("#myId").keyup(function(event){
    console.log(this.selectionStart);
    if(this.selectionStart < 2){
        this.selectionStart = 2;
        console.log(this.selectionStart);
        event.preventDefault();
    }
});

小提琴此处