Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

javascript - Spacebar triggering click event on checkbox?

If you spacebar on a checkbox, it checks the box. Everything was fine until I decide to disable the click event on the parent div, which I realized, disabled the spacebar on the checkbox as well!

div1.addEventListener("click",function (e) {
  if (e.preventDefault) e.preventDefault();
  e.cancelBubble = true;
  return false;
}, true);
<div id="div1">
    <input id="chk1" type="checkbox">
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quirksmode - click, mousedown, mouseup, dblclick

The click event fires when the user clicks on an element OR activates an element by other means (i.e. the keyboard) ... “click” event is really a misnomer: it should be called the “activate” event.

To work around this, you can attach a click and keyup event to the checkbox.

checkbox.addEventListener("click", handleCheckboxEvent, true);
checkbox.addEventListener("keyup", handleCheckboxEvent, true);

Listen to both events, and always disable the default behavior. From there, you can determine if the spacebar fired a keyup event if the key 32 is pressed (e.keyCode === 32).

If so, manually check the checkbox if it is not checked, and uncheck it if it is checked.

function handleCheckboxEvent(e) {
    e.preventDefault();

    if (e.keyCode === 32) {  // If spacebar fired the event
        this.checked = !this.checked;
    }
}

Updated Example - tested in the latest versions of Chrome/FF/IE.

(function () {
    var checkbox = document.getElementById('checkbox');

    function handleCheckboxEvent(e) {
        e.preventDefault();

        if (e.keyCode === 32) {  // If spacebar fired the event
            this.checked = !this.checked;
        }
    }

    checkbox.addEventListener("click", handleCheckboxEvent, true);
    checkbox.addEventListener("keyup", handleCheckboxEvent, true);
})();
<input id="checkbox" type="checkbox" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...