強くはこれをしないことをおすすめします。input type="checkbox"
をlabel
と組み合わせて使用してください。それが彼らのためのものです。それらを非常に徹底的にスタイルすることができます。 input type="checkbox"
を非表示にすることもできます。表示する場合は、label
のみを表示します。
しかし、あなたはinput
を使用することはできません。そう、はい、keypress
ハンドラでこれを行うことができます。あなたはおそらくまた、クリックを処理したいと思うでしょう。コメントを参照してください:
// Handle toggline the "checkbox"
// Expects the element as `this` and the event as `e`
function toggleFakeCheckbox(e) {
// States as far as I can tell from
// https://www.w3.org/TR/wai-aria/states_and_properties#aria-checked
// and
// https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_checkbox_role
this.setAttribute(
"aria-checked",
this.getAttribute("aria-checked") === "true" ? "false" : "true"
);
// Avoid the default (spacebar in particular is problematic)
e.preventDefault();
e.stopPropagation();
}
// Get the element
var sample = document.querySelector(".sample");
// Set up its handlers for click and keypress
sample.addEventListener("click", toggleFakeCheckbox);
sample.addEventListener("keypress", function(e) {
// Flag for whether to toggle
var toggle = false;
var keyCode;
if ("key" in e) {
// Modern user agent
toggle = e.key === " " || e.key === "Enter";
} else {
// Fallback for older user agents
keyCode = e.which || e.keyCode;
toggle = keyCode === 32 || keyCode === 13;
}
if (toggle) {
toggleFakeCheckbox.call(this, e);
}
});
// Give it focus for easy testing
sample.focus();
/* Let's show the state of the checkbox */
[role=checkbox][aria-checked=true]:before {
content: '[x] '
}
[role=checkbox][aria-checked=false]:before {
content: '[ ] '
}
<span class="sample" tabindex="0" role="checkbox" aria-checked="true" aria-decribedby="">Checkbox</span>
しかし、再び:車輪の再発明することは、あなたがそうするとき、すべてのARIAのルールを尊重しようとしていても、良いことではありません...
アップデート:IEでスパンをフォーカスしてスペースバーを押すと、デフォルトのアクション(Firefoxでこれを止めるには十分)が妨げられて伝播が停止したにもかかわらず、ページの別の部分に移動します。それはなぜそれをするのですか?我々は車輪を再発明しようとしたからです。 Bad Thing™はどれですか?
チェックボックスを使用しないでください。このチェックボックスは、この機能が組み込まれていて、必要な方法でスタイルを設定できます。 –
私はすでにチェックボックスを使用していますが、チェック/チェックを解除できませんか? –
上記のマークアップにチェックボックスはありません。 –