Javascript 可以在不使用“for=id”的情况下将标签与复选框相关联吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8537621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:25:29  来源:igfitidea点击:

Possible to associate label with checkbox without using "for=id"?

javascriptjqueryhtmlcsscheckbox

提问by D.Tate

I know that it is good sometimes to associate a label with a checkbox:

我知道有时将标签与复选框相关联是好的:

<input id="something" type="checkbox" value="somevalue" />
<label for="something">this is label text</label>

..but do I haveto use an id to associate it?
The main reason I even care is because I like being able to click a label to toggle the checkbox value, but don't like the idea of using an id for something so simple.

..但是我必须使用 id 来关联它吗?
我什至关心的主要原因是因为我喜欢能够单击标签来切换复选框值,但不喜欢将 id 用于如此简单的事情的想法。

I guess I could use jQuery toggle the previous element (checkbox) of a clicked label, but maybe there is something simpler I'm missing. https://stackoverflow.com/a/2720771/923817looked like a solution, but the user said it doesn't work in IE.

我想我可以使用 jQuery 切换单击标签的前一个元素(复选框),但也许我缺少一些更简单的东西。https://stackoverflow.com/a/2720771/923817看起来像一个解决方案,但用户说它在 IE 中不起作用。

回答by Madara's Ghost

Yes, place the input inside the label.

是的,将输入放在标签内。

<label><input type=checkbox name=chkbx1> Label here</label>

See implicit label associationin the HTML specifications.

请参阅HTML 规范中的隐式标签关联

回答by egor.xyz

Demo: JsFiddle

演示:JsFiddle

.c-custom-checkbox {
  padding-left: 20px;
  position: relative;
  cursor: pointer;
}
.c-custom-checkbox input[type=checkbox] {
  position: absolute;
  opacity: 0;
  overflow: hidden;
  clip: rect(0 0 0 0);
  height: 15px;
  width: 15px;
  padding: 0;
  border: 0;
  left: 0;
}
.c-custom-checkbox .c-custom-checkbox__img {
  display: inline;
  position: absolute;
  left: 0;
  width: 15px;
  height: 15px;
  background-image: none;
  background-color: #fff;
  color: #000;
  border: 1px solid #333;
  border-radius: 3px;
  cursor: pointer;
}
.c-custom-checkbox input[type=checkbox]:checked + .c-custom-checkbox__img {
  background-position: 0 0;
  background-color: tomato;
}
<label class="c-custom-checkbox">
  <input type="checkbox" id="valueCheck" />
  <i class="c-custom-checkbox__img"></i>Some Label
</label>

回答by Web Designer cum Promoter

<label for="something">this is label text</label>
<input id="something" type="checkbox" value="somevalue" />

actually the for attribute was used for screen readers to disabled persons, so not useful for accessibility to write without for attribute

实际上 for 属性是用于屏幕阅读器给残疾人使用的,因此对于没有 for 属性的可访问性写入没有用