鉴于HTMLInputElement
, HTMLSelectElement
和 HTMLTextAreaElement
全部直接继承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>
最佳答案
<label>
元素可以关联到可标记元素。
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.
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/