我想使用“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');
});
答案 0 :(得分:4)
你只需要focus
div:
let div = document.querySelector('div');
div.focus();

<div contenteditable="true">Div Content</div>
&#13;
答案 1 :(得分:3)
如果我理解正确,你要做的就是将焦点设置在元素上。由于您已启用contenteditable
,因此以下内容应足够:
editArea.setAttribute('contenteditable', true);
editArea.focus(); // Focus on the input which will activate editing