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

前端 未结 8 1571
太阳男子
太阳男子 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 09:08

    You could do this (just an outlined idea, no code):

    Devise a regex that matches your entire text. Use fixed strings for the unmodifiable parts, and use [\s\S]*? for the modifiable parts. Use ^ and $ to anchor your regex.

    /^This is fixed text\. Now something editable:[\s\S]*?Now fixed again\.$/
    

    Now react to the keyup event, and probably other events as well (like paste).

    With every relevant event, make a check if the regex still matches.

    If it doesn't, cancel the event.

    Effectively, this should stop modifications to parts that are literal in the regex and thus make certain parts of your text read-only.

    Don't forget to test the string on the server side as well after the form post - never trust that the client cannot send invalid values.


    EDIT

    You can use a regex quote function to dynamically build that regex from strings, this should save you a lot of the hassle.

    function regexQuote(s) { return s.replace(/[\[\]^$*+?{}.|\\]/g, "\\$&") }
    

    usage

    var re = new Regex(
      "^" + 
      [regexQuote(fixedPart1), regexQuote(fixedPart2)].join("[\\s\\S].*?")
       + "$"
    );
    
    0 讨论(0)
  • 2020-11-29 09:12

    Interesting idea, but sadly, the text within the text area must be treated uniformly, i.e. you can't disable a subsection of the text area contents.

    You do have options, however. If you can identify the text that needs to be disabled, you can add it as a DOM element (i.e. a div), and then position it in a way that implies it is inside the text area.

    You can imply that this div is inside the text area either by making the text area big and using position: relative/absolute styles to move the div over the text area. Or, you can remove the border on the text area and put it on a container that also contains the div w/ "disabled" text.

    0 讨论(0)
提交回复
热议问题