当另一个输入聚焦时,contenteditable div失去选择 [英] contenteditable div loses selection when another input focuses

查看:136
本文介绍了当另一个输入聚焦时,contenteditable div失去选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的contenteditable div有问题。当我想在其上执行一个简单的命令(如粗体或斜体)时,我将执行以下操作:

I have a problem with contenteditable div. When i want to execute a simple command (like bold or italic) on it, i do the following:


  • 存储div(因为它在单击粗体按钮后将失去焦点)

  • 在单击按钮时,我将div调整为焦点并执行粗体命令

  • 一切正常
  • >
  • memorize the div (since it will lose focus after i click on bold button)
  • on button click, i refocus the div and execute the bold command
  • everything works

现在,当我尝试做一些更困难的事情时,就会出现问题。例如,我想显示一个带有输入字段的自定义对话框:

Now the problem occurs when i try to do something more difficult. For instance, i want to show a custom dialog with an input field:


  • 存储div

  • 单击按钮时,将显示一个对话框(一切仍然正常)

  • 用户将输入字段放在该对话框上(这就是一切中断的地方)

这个问题是一旦输入元素被聚焦,不仅我的contenteditable div失去了焦点-它也失去了选择并将光标移到开头

The problem with this is that as soon as an input element is focused, not only that my contenteditable div loses focus - it also loses the selection and moves the cursor to the beginning as soon as i refocus it.

所以我的问题是:在关注另一个输入元素之后,如何防止contenteditable div失去选择?

So my question is: how do i prevent a contenteditable div to lose its selection after i focus on another input element?

推荐答案

如果input和contenteditable元素在同一文档中,则将无法防止contenteditable元素中的选择被破坏。但是,您可以做的是在输入框获得焦点之前保存选择,并在取消对话框之后恢复选择。

If the input and contenteditable element are within the same document, you won't be able to prevent the selection in the contenteditable element from being destroyed. However, what you can do is save the selection before the input box receives focus and restore the selection after the dialog is dismissed.

下面是一些简单的示例代码:

Here is some simple example code:

https://stackoverflow.com/a/3316483/96100

这是一个更完整的示例:

And here's a fuller example:

https://stackoverflow.com/a/4690057/96100

如果将input或contenteditable元素放在单独的位置iframe,大多数浏览器(尽管不是IE)都会保留原始选择。

If you place either the input or contenteditable element within a separate iframe, most browsers (although not IE) will preserve the original selection.

这篇关于当另一个输入聚焦时,contenteditable div失去选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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