javascript 有没有办法使文本区域部分可编辑?(仅使部分文本可编辑)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5444874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:13:06  来源:igfitidea点击:

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

javascriptjquerytextarea

提问by Kenji Kina

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 are not ("greyed out", so to speak).

我刚刚遇到了一种情况,在这种情况下,只有文本区域的一部分(以前加载了文本)可编辑而其他部分不可编辑(可以说是“变灰”),这将是一个优雅的解决方案。

Is this possible at all by using javascript in general?

一般来说,这完全可以通过使用 javascript 来实现吗?

I would be using jQuery.

我会使用jQuery。

采纳答案by Tomalak

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.

设计一个与整个文本匹配的正则表达式。不可修改部分使用固定字符串,可修改部分使用固定字符串[\s\S]*?。使用^$来锚定您的正则表达式。

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

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

现在对keyup事件做出反应,可能还有其他事件(如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].*?")
   + "$"
);

回答by Phil.Wheeler

If you're using a plain textarea element, you won't be able to style up the required content (based on whether or not that content is editable). At best you'd be able to check to see whether the content your user is trying to change is on either the blacklist or whitelist and then stop the edit or not accordingly. You might also provide some visual feedback like a warning message saying "you can't do that".

如果您使用纯 textarea 元素,您将无法设置所需内容的样式(基于该内容是否可编辑)。充其量您可以检查您的用户尝试更改的内容是否在黑名单或白名单中,然后相应地停止编辑。您还可以提供一些视觉反馈,例如警告消息“您不能这样做”。

My recommendation would be to take advantage of the contenteditableattribute, which might take a bit more time to style but will allow you much greater flexibility in the long run.

我的建议是利用contenteditable属性,这可能需要更多的时间来设计样式,但从长远来看会让你有更大的灵活性。

You would be able to style up a div element to look much like your required textarea, then use editable spans within that to set whether or not a particular block of text can be edited. You could then use JavaScript commands (refer to the link above) or use a "save" button to retrieve this content, set it as the value for your actual textarea (which you could have hidden) and post your page back as normal.

您可以将 div 元素的样式设置为与您所需的 textarea 非常相似,然后在其中使用可编辑的跨度来设置是否可以编辑特定的文本块。然后,您可以使用 JavaScript 命令(请参阅上面的链接)或使用“保存”按钮来检索此内容,将其设置为实际 textarea(您可以隐藏)的值,然后照常发布您的页面。

Use the following code as a rough example.

使用以下代码作为粗略示例。

<div id="editable-content">
    <span id="block1" class="editable" contenteditable="true">This is some editable content which will </span>
    <span id="block2" class="non-editable">quickly be followed by some non-editable content</span>
</div>
<div style="display: none;">
    <textarea id="PostedContent"></textarea>
</div>
<div>
    <input id="save-page" type="submit" value="Save Page" />
</div>

<script type="text/javascript">
    $(function () {
        $('#save-page').click(function () {
            $('#PostedContent').val($('#editable-content').text());
        });
    });
</script>

回答by aquinas

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

嗯,你可以做这样的事情。这段代码效率很低,我只是想概述一下这个概念。

JS:

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

HTML

<textarea id="t" rows=5 cols="80">Hello this is a test @{stuff} 

        this part is editable @{other stuff}     

    </textarea>

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.

这使用了您对“标记”的概念。一般的想法是说好的,用户尝试编辑的文本范围是否在我们的标记之一内?显然,每次按下一个键时使用正则表达式并不是确定这一点的最佳方法,我没有忽略箭头键等,但这给了你一个大致的想法。

回答by David says reinstate Monica

I'd suggest, rather than trying to break the contents of an inputinto sub-strings of editable/non-editable content, you use the contentEditableattribute of an HTML element, and use JavaScript to pass that edited value into a hidden inputelsewhere in the page.

我建议,与其尝试将 an 的内容分解input为可编辑/不可编辑内容的子字符串,不如使用contentEditableHTML 元素的属性,并使用 JavaScript 将该编辑后的值传递到input页面其他位置的隐藏中.

回答by typeof

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.

但是,您确实有选择。如果您可以识别需要禁用的文本,则可以将其添加为 DOM 元素(即 div),然后以暗示它位于文本区域内的方式放置它。

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.

您可以通过使文本区域变大并使用 position:relative/absolute 样式将 div 移动到文本区域上来暗示此 div 位于文本区域内。或者,您可以移除文本区域上的边框并将其放在一个容器上,该容器还包含带有“禁用”文本的 div。

回答by Sunil Jakhar

After searching find it's really hard to make a text area partially editable

搜索后发现很难使文本区域部分可编辑

Here is my code that i used for this requirement

这是我用于此要求的代码

input
{
  width:100%;
  border:0px solid;
  outline:none
}

 
<!DOCTYPE html>
   <html>     
<div style="padding: 2px;border:1px solid #ccc;width: 82%;max-height:100px;min-height: 51px;overflow:auto;outline: none;resize: both;" contenteditable="true" unselectable="on">    
    

  <input placeholder="enter prefix..." value="editable postfix..." ></input>
  <div id='unEditable' style="background-color:yellow;width: fit-content;padding-left:10px;padding-right:10px;border-radius:10px;height: fit-content;" contenteditable="false" unselectable="off" onkeyup="" >
         fixed content non-editable
        
   </div>
  <input placeholder="enter postfix..." value="editable prefix..." style='width:97%'></input>
    
 </div>
</html>

回答by Carmela

In a parent element, you can set the border to 1px solid gray and then inside this, put the

在父元素中,您可以将边框设置为 1px 纯灰色,然后在其中放置

1) textarea (modify the css to not have border) 2) label (no border as well)

1) textarea (修改css使其没有边框) 2) label (也没有边框)

In this case, it will look like the both texts inside 1) and 2) are together since they are placed in one box. 1) Is editable though while the other is grayed out.

在这种情况下,1) 和 2) 中的两个文本看起来像在一起,因为它们被放在一个盒子里。1) 是可编辑的,而另一个是灰色的。

回答by Anthony John Ramirez Llanos

I would suggest two textareas one readonly and another editable one, overlapping so it looks like its only one

我会建议两个 textareas 一个只读的和另一个可编辑的,重叠所以它看起来像它唯一的