如何以编程方式启动/停止编辑一个contenteditable?

时间:2021-10-27 21:16:00

What kind of event do I need to fire to programmatically start or stop actually editing a contenteditable, like when the user focuses or blurs it? I tried .focus(), .click(), setting the selection to its content, but none of them seem to work.

我需要触发什么样的事件来以编程方式启动或停止编辑contenteditable,比如当用户关注或模糊它时?我尝试了.focus()、.click(),将选择设置为其内容,但它们似乎都不起作用。

EDIT: .focus() does work, just make sure the contenteditable node is already inserted to the document...

编辑:.focus()确实有效,只需确保已经将contenteditable节点插入到文档中……

2 个解决方案

#1


4  

You can use the trigger() method inside jQuery:

您可以在jQuery内部使用触发器()方法:

$('div[contenteditable="true"]').trigger('focus');

This will cause the caret to appear on page load, as per this jsFIddle demo.

这将导致插入符号出现在页面加载上,正如这个jsFIddle演示文件所示。

#2


1  

Maybe you are looking for disabled and readonly attributes.

也许您正在寻找禁用的和只读的属性。

HTML:
<input type="text" disabled="disabled" />

Javascript:
document.getElementsByTagName("div")[0].setAttribute("disabled", "disabled");

other option is

其他选项是

HTML:
<input type="text" readonly="readonly" />

Javascript:
document.getElementsByTagName("div")[0].setAttribute("readonly", "readonly");

#1


4  

You can use the trigger() method inside jQuery:

您可以在jQuery内部使用触发器()方法:

$('div[contenteditable="true"]').trigger('focus');

This will cause the caret to appear on page load, as per this jsFIddle demo.

这将导致插入符号出现在页面加载上,正如这个jsFIddle演示文件所示。

#2


1  

Maybe you are looking for disabled and readonly attributes.

也许您正在寻找禁用的和只读的属性。

HTML:
<input type="text" disabled="disabled" />

Javascript:
document.getElementsByTagName("div")[0].setAttribute("disabled", "disabled");

other option is

其他选项是

HTML:
<input type="text" readonly="readonly" />

Javascript:
document.getElementsByTagName("div")[0].setAttribute("readonly", "readonly");