Is there a way to make a text area partially editable? (make only portions of the text editable)

前端 未结 8 1619
太阳男子
太阳男子 2020-11-29 08:09

I just came across a situation in which it would be an elegant solution to have only portions of a text area (previously loaded with text) be editable while other portions a

8条回答
  •  野性不改
    2020-11-29 08:52

    Well, you could do something like this. This code is very inefficient, I'm just trying to outline the concept.

    JS:

    $(function () {
                var tb = $("#t").get(0);
                $("#t").keydown(function (event) {
                    var start = tb.selectionStart;
                    var end = tb.selectionEnd;
                    var reg = new RegExp("(@{.+?})", "g");
                    var amatch = null;
                    while ((amatch = reg.exec(tb.value)) != null) {
                        var thisMatchStart = amatch.index;
                        var thisMatchEnd = amatch.index + amatch[0].length;
                        if (start <= thisMatchStart && end > thisMatchStart) {
                            event.preventDefault();
                            return false;
                        }
                        else if (start > thisMatchStart && start < thisMatchEnd) {
                            event.preventDefault();
                            return false;
                        }
                    }
                });
            });
    

    HTML

    
    

    This uses your idea of "markers." The general idea is to say ok, is the text range that the user is trying to edit inside of one of our markers? Obviously, using a regexp everytime a key is pressed is not the best way to determine this, I'm not ignoring arrows keys, etc. etc. but this gives you a general idea.

提交回复
热议问题