Can the label tags for attribute be associated with a normal div?

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

is it valid html under html5 definitions to use a label's "for" value as an id of a normal div element (for example I have made a custom dropdown list implementation which is encased inside a div)

Please let me know if possible,

Thomas

回答1:

Not according to the spec:

Some elements, not all of them form-associated, are categorized as labelable elements. These are elements that can be associated with a label element.

"button" "input" (if the type attribute is not in the hidden state) "keygen" "meter" "output" "progress" "select" "textarea"

http://www.w3.org/TR/html5/forms.html#category-label

See also:

The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable element in the same Document as the label element. If the attribute is specified and there is an element in the Document whose ID is equal to the value of the for attribute, and the first such element is a labelable element, then that element is the label element's labeled control.

http://www.w3.org/TR/html5/the-label-element.html#attr-label-for

I do think the question presents a valid use case. I'm not sure what the recommended pattern is for such a scenario, though ARIA attributes might help to make the markup more accessible:

https://developer.mozilla.org/en/Accessibility/ARIA/forms/Basic_form_hints https://developer.mozilla.org/Special:Tags?tag=ARIA



回答2:

As Tim noted it is not possible to do it natively, however with a little bit of javascript you can simulate it

jQuery(document).delegate('[for]','click',function(e){     var targetEl = jQuery('#'+jQuery(this).attr('for'));     if(targetEl.is('div.your-custom-dropdown-class')) { //if targetEl is one of your dropdowns         e.preventDefault();         targetEl.trigger('click'); //open the drop down     } });


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!