onmousedown事件对象的行为异常 [英] onmousedown event object behaving strangely

查看:59
本文介绍了onmousedown事件对象的行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!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); 所在位置,复选框单击的行为符合预期:所有左键单击均选中该复选框,所有右键单击均取消选中该复选框。

If I leave the line alert(e.button); where it is, checkbox clicking behaves as expected: all left-clicks check the checkbox, and all right-clicks uncheck the checkbox.

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

If I remove the code alert(e.button);, then all of a sudden, a left-click will check and then immediately uncheck the checkbox, and a right-click will do nothing but open the context menu.

为什么会发生这种情况?而我该怎么做才能使其表现如我在第一段中所述,但是没有 alert(e.button);

Why does this happen? and What can I do to make it behave as I described it in the first paragraph but without alert(e.button);?

推荐答案

您可以尝试将点击事件分为 onlick (用于左键单击)和 oncontextmenu (用于右键单击)。
还请记住返回false; 以防止显示内容菜单。

You can try by separating click events to onlick (for left click) and oncontextmenu (for right click). Also remember return false; to prevent showing content menu.

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>

这篇关于onmousedown事件对象的行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆