如何在用户键入时突出显示文本部分?
我有一个用户可以输入的页面文本框。当用户输入时,我想突出显示文本部分。为了简单起见,我现在只是想突出显示所有元音。
代码的第一部分来自这个问题:
$('[contenteditable]').live('focus', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).live('blur keyup paste', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
然后我可以从中编写this:
var magicRegex = /[aeiou]/gi;
$('#message').change(function() {
$(this).find('br').replaceWith('\n');
var message = $(this).text();
message = message.replace(magicRegex , '<mark>$&</mark>');
message = message.replace(/\n/gi, '<br />');
$(this).html(message);
}).change();
此代码在用户键入时突出显示元音。然而,这样做时,每次突出显示更新时,该字段的焦点都会丢失,并且用户必须再次单击才能键入另一个字符。
我该如何解决这个问题?
I have a page textbox that a user can type in. As the user types, I want to highlight sections of text. To keep things simple, I'm just trying to highlight all vowels at the moment.
The first part of the code is from this question:
$('[contenteditable]').live('focus', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).live('blur keyup paste', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
From which I can then write this:
var magicRegex = /[aeiou]/gi;
$('#message').change(function() {
$(this).find('br').replaceWith('\n');
var message = $(this).text();
message = message.replace(magicRegex , '<mark>amp;</mark>');
message = message.replace(/\n/gi, '<br />');
$(this).html(message);
}).change();
This code highlights vowels as the user types. However, in doing so, the focus on the field is lost every time the highlighting updates, and the user must click again to type another character.
How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很确定如果不生成模仿场就无法做到这一点。
您可以使用 HTML 生成看起来像输入字段的 HTML 元素。然后,当该元素获得焦点时,您可以捕获击键。您必须跟踪特殊的非字符键,例如退格键、制表符等,并单独处理它们。无论用户输入什么内容,都可以存储到真实的表单字段中(或者如果您选择,也可以存储到 JavaScript 变量中)。
然后,模仿字段将读取实际值(存储在表单字段或 JS 变量中)并渲染它(使用 CSS、DOM 元素等),使其看起来好像某些字符突出显示(或任何您想要做的事情)与他们)。
我不知道还有什么其他方法可以完成你想要做的事情。
祝你好运。
I'm pretty sure that you can't do this without generating an imitation field.
You could use HTML to generate an HTML element that looks like an input field. Then when that element has focus you can capture key strokes. You'll have to track special non-character keys like backspace, tab, etc and deal with those individually. Whatever the user types can be stored into a real form field (or just a JavaScript variable if you choose).
The imitation field would then read the actual values (stored in the form field or JS variable) and render it (with CSS, DOM elements, etc) to make it appear as if certain characters are highlighted (or whatever you'd like to do with them).
I don't know of any other way you could accomplish what you are trying to do.
Good luck.