如何触发' contenteditable'元素使用js进入编辑状态?

时间:2017-01-21 07:21:16

标签: javascript html html5

我想使用“contenteditable'”来实现元素插入编辑。属性。是否可以使用鼠标事件模拟而不是用户单击进入编辑状态?

function triggerEvent(element, eventType) {
    let rect = element.getBoundingClientRect();
  console.log(rect);

    let event = new MouseEvent(eventType, {
    clientX: rect.left + 20,
    clientY: rect.top + 10,
    view: window,
    buttons: 1,
    bubbles: true,
  });
  element.dispatchEvent(event);
}

document.getElementById('btn').addEventListener('click', (event) => {
    let editArea = document.getElementById('edit-area');
  editArea.setAttribute('contenteditable', true);

  triggerEvent(editArea, 'mousedown');
});

DEMO:https://jsfiddle.net/lfree/vkeq9fza/1/

2 个答案:

答案 0 :(得分:4)

你只需要focus div:



let div = document.querySelector('div');

div.focus();

<div contenteditable="true">Div Content</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

如果我理解正确,你要做的就是将焦点设置在元素上。由于您已启用contenteditable,因此以下内容应足够:

editArea.setAttribute('contenteditable', true);
editArea.focus(); // Focus on the input which will activate editing