tabIndex doesn't make a label focusable using Tab key

前端 未结 5 2058
夕颜
夕颜 2021-01-31 02:32

I\'m trying to replace checkbox/radio inputs with icons. For this, I need to hide the original checkbox/radio. The problem is, I also want the form to properly support keyboard

5条回答
  •  隐瞒了意图╮
    2021-01-31 03:04

    Edit: The following was a misreading of the spec:

    Looking that the full specification, you'll see that there is something called tabindex focus flag, which defines if the tabindex attribute will actually make the field "tabbable". The label element is missing from that list of suggested elements.

    But then again, so is the span element, so go figure :).

    That said, yYou can make the label text focusable by wrapping the whole thing in an another element, or using some JavaScript to force the issue. Unfortunately, wrapping (here in an anchor) can men a fair amount of extra work in CSS and JS to get working like a normal label element.

    document.getElementById('checkbox').addEventListener('change', function(event) {
      document.getElementById('val').innerHTML = event.target.checked;
    });
    document.getElementsByClassName('label')[0].addEventListener('click', function(event) {
      event.target.getElementsByTagName('label')[0].click();
      event.preventDefault();
    });
    document.getElementsByClassName('label')[0].addEventListener('keypress', function(event) {
      if ((event.key || event.which || event.keyCode) === 32) {
        event.target.getElementsByTagName('label')[0].click();
        event.preventDefault();
      }
    });
    .label,
    .label:visited,
    .label:hover,
    .label:active {
      text-decoration: none;
      color: black;
    }
    span with tabindex

提交回复
热议问题