blog icon indicating copy to clipboard operation
blog copied to clipboard

html5 “contenteditable” 属性模拟 input,让 div 可编辑

Open yangchch6 opened this issue 5 years ago • 0 comments

html 原生的 focus 方法适用于:input、select、button、textarea、radio、checkbox 等元素。 实际开发场景中,可能需要用 div 替代表单元素,或是在 div 上调用 focus() 方法。 那么最简单粗暴的方法就是:添加 contenteditable 属性。

<div contenteditable="true" id="myText">这是一段可编辑的段落。请试着编辑该文本。</div>

然后就可以像 input 一样,调用 focus() 和 blur() 方法。

function getfocus() {
    document.getElementById("myText").focus();
}

function losefocus() {
    document.getElementById("myText").blur();
}

补充一点:哪些HTML元素可以接收焦点?(包括键盘导航聚焦)

a[href],  // a 标签有 href 属性
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true] {
    &:not([tabindex='-1']) {
        /* your SCSS for focusable elements goes here */
    }
}

属性说明:

  1. contenteditable:true | false 规定元素文本是否可编辑;
  2. tabindex:0 | -1 | x 0:tab键可获取焦点; -1:tab键不可获取焦点; x:x>0,x越小获取焦点优先级越高;值相同时,按照 DOM 顺序。

yangchch6 avatar Feb 18 '20 06:02 yangchch6