最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to programmatically startstop editing a contenteditable? - Stack Overflow

programmeradmin3浏览0评论

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.

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

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.

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

Share Improve this question edited May 23, 2017 at 12:13 CommunityBot 11 silver badge asked Jan 24, 2014 at 23:06 thSoftthSoft 22.7k6 gold badges96 silver badges105 bronze badges 5
  • you mean toggle the contenteditable attrib? – dandavis Commented Jan 24, 2014 at 23:08
  • No, it is already contenteditable. – thSoft Commented Jan 24, 2014 at 23:10
  • keyup, keydown, keypress? – BenM Commented Jan 24, 2014 at 23:14
  • What do you mean "start" or "stop" editing the element? The user is the one who starts or stops editing. Are you looking for an event to fire when they have done that? – Elliot Bonneville Commented Jan 24, 2014 at 23:15
  • 1 When a user clicks in a contenteditable, a caret shows up and it responds to editing keyboard events. I want to activate this "editing mode" from JavaScript. – thSoft Commented Jan 24, 2014 at 23:18
Add a ment  | 

2 Answers 2

Reset to default 5

You can use the trigger() method inside jQuery:

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

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

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");
发布评论

评论列表(0)

  1. 暂无评论