onmousedown事件对象表现得很奇怪

时间:2017-03-03 02:46:33

标签: javascript html checkbox

<!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>testing</title>
        </head>
        <body>
            <input type="checkbox" id="test">
            <script>
                var t = document.getElementById("test");
                t.onmousedown = function(e) {
                    if (e.button === 0)
                        t.checked = true;
                    else if (e.button === 2)
                        t.checked = false;

                    alert(e.button);
                }
            </script>
        </body>
    </html>

如果我将行alert(e.button);留在原来的位置,则复选框点击会按预期运行:所有左键单击都会选中复选框,所有右键单击都会取消选中该复选框。

如果我删除了代码alert(e.button);,那么突然间,左键单击将会检查,然后立即取消选中该复选框,右键单击将不会执行任何操作,只需打开上下文菜单。

为什么会这样?我能做些什么才能让它像我在第一段中描述的那样表现但没有alert(e.button);

2 个答案:

答案 0 :(得分:4)

您可以尝试将点击事件分为onlick(左键单击)和oncontextmenu(右键单击)。 另请记住return false;以阻止显示内容菜单。

var t = document.getElementById("test");

t.onclick = function(e) {
  t.checked = true;
}
t.oncontextmenu = function(e){
  t.checked = false;
  return false;
}
                
  <html>
      <head>
          <meta charset="utf-8">
          <title>testing</title>
      </head>
      <body>
          <input type="checkbox" id="test">
      </body>
  </html>

答案 1 :(得分:1)

解释行为

来自W3 schools onmousedown Event

  

与onmousedown事件相关的事件顺序(对于左/中鼠标)   按钮):

     
      
  1. onmousedown
  2.   
  3. onmouseup
  4.   
  5. 的onclick
  6.         

    与onmousedown事件相关的事件顺序(右边   鼠标按钮):

         
        
    1. onmousedown
    2.   
    3. onmouseup
    4.   
    5. oncontextmenu
    6.   

浏览器会“检查”onclick事件的复选框,因为您可以看到onmousedown事件发生之前。

alert(e.button)触发时,下一个事件的流被消息框中断,因此onclick事件永远不会发生,并且您的代码通过设置checked属性来检查复选框。如果您没有alert(e.button),则代码会选中复选框,onclick事件会立即取消选中。

解决方案

  

请参阅Ngoan Tran's answer,他的解决方案要远胜于此。

一个解决方案可能是在复选框上方创建一个可引用的div,尽管这可能会增加可用性问题。

.container-div {
  position:relative;
}
.clicable-div {
  position:absolute;
  height:100%;
  width:100%;
  top:0;
  left:0;
  z-index:1;
}
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>testing</title>
    </head>
    <body>
        <div class="container-div">
          <div class="clicable-div" id="clicable"></div>
          <input type="checkbox" id="test">
        </div>
        <script>
            var t = document.getElementById("clicable");
            var c = document.getElementById("test");
            t.onmousedown = function(e) {
                if (e.button === 0)
                    c.checked = true;
                else if (e.button === 2)
                    c.checked = false;
            };
            //Disables the contextual menu on right button click!
            t.oncontextmenu = function() {
              return false;
            };
        </script>
    </body>
</html>

相关问题