有没有办法让文本区域部分可编辑? (仅使部分文本可编辑) [英] Is there a way to make a text area partially editable? (make only portions of the text editable)

查看:178
本文介绍了有没有办法让文本区域部分可编辑? (仅使部分文本可编辑)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到一种情况,它只是一个优雅的解决方案,只有部分文本区域(以前加载文本)可编辑而其他部分不可编辑(灰色,可以这么说)。 / p>

这一般是否可以使用javascript?



我会使用jQuery。

解决方案

你可以这样做(只是一个概述的想法,没有代码):



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

  / ^这是固定的text\。现在可编辑的东西:[\\\\ S] *?现在再次固定\。$ / 

现在对 keyup 事件作出反应,也可能对其他事件做出反应(例如粘贴)。



对于每个相关事件,请检查正则表达式是否仍然匹配。



如果没有,请取消该事件。



实际上,这应该停止对正则表达式中字面意思的部分的修改,从而使文本的某些部分成为只读。



不要忘记在表单发布后测试服务器端的字符串 - 永远不要相信客户端无法发送无效值。






编辑



您可以使用正则表达式引用函数从字符串动态构建该正则表达式,这应该为你省去了很多麻烦。

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

用法

  var re = new Regex(
^+
[regexQuote(fixedPart1),regexQuote(fixedPart2)]。join([\\\\\\ S]。*?)
+$
);


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?

I would be using jQuery.

解决方案

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].*?")
   + "$"
);

这篇关于有没有办法让文本区域部分可编辑? (仅使部分文本可编辑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆