javascript - 带有 for=DIV-ID 的 HTML <label> 聚焦一个内容可编辑的 div(标签 <label> 只支持表单元素吗?)

标签 javascript html

鉴于HTMLInputElement , HTMLSelectElementHTMLTextAreaElement全部直接继承HTMLElement (而不是常见的东西,如 HTMLFormElement),我希望 <label>将能够关注非字段元素,例如 <div> .

但是,下面的代码示例显示了一个 <label>正确聚焦 <textarea> ,但需要 JS hack(在示例中使用 jQuery)来聚焦内容可编辑的 <div> .

是否有已发布的元素列表 <label>一起工作?或任何讨论 with contenteditable <div> 用法的文档秒?我是否遗漏了什么,也许不需要 JS 来关注内容可编辑的 <div>

<div>
  <label for="textarea-id" style="font-weight:bold;">Label Text Area</label><br>
  <textarea id="textarea-id">
Editable text
  </textarea>
</div>

<div style="margin-top:20px">
  <label for="contenteditable-id" id="label-for-div-id" style="font-weight:bold;">Label Editable Div</label><br>
  <div id="contenteditable-id" contenteditable="true" style="border:solid 1px black">
    <p>
      <span>Edtiable text</span>
    </p>
  </div>
</div>
<script>
$(function() {
  $('#label-for-div-id').on('click', function() {
    $('#' + $(this).attr('for')).focus();
  })
})
</script>

发布于https://jsfiddle.net/jkvsd03y/5/

最佳答案

<label>元素可以关联到可标记元素

来自label Element doc :

for

The id of a labelable form-related element in the same document as the element. The first element in the document with an id matching the value of the for attribute is the labeled control for this label element, if it is a labelable element. If it is not labelable then the for attribute has no effect. If there are other elements which also match the id value, later in the document, they are not considered.

来自Content Categories doc :

labelable

Elements that can be associated with <label> elements. Contains <button>, <input>, <keygen>, <meter>, <output>, <progress>, <select>, and <textarea>.

关于javascript - 带有 for=DIV-ID 的 HTML <label> 聚焦一个内容可编辑的 div(标签 <label> 只支持表单元素吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54792126/

相关文章:

javascript - 事件触发后聚焦于某个元素

javascript - 从文本框获取值 - Android WebView 和 JavascriptInterface 问题

html - Flex 元素在 Safari 中无法正确堆叠

javascript - 在页面上禁用链接的最佳方法是什么?

javascript - 根据 JS 中输入的值显示警报?

html - 使用 node.js 中的 XSLT 样式表将 xml 转换为 html

html - 固定到包装器 div 的背景附件

html - CSS 在一行中获取 4 个列表项

java - Vaadin动态加载JavaScript、CustomLayout

Javascript 访问父属性