按钮和div的onclick事件有什么区别?

What's the difference between onclick events of buttons and divs?

首先,这可能只适用于 Firefox,但我不确定。让我们从一些代码开始:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Editor</title>
    <!-- styling -->
</head>
<body>
    <button id="bold" onclick="executeAction('bold')"  >
        Bold
    </button>
    <div id="italic"  onclick="executeAction('italic')">
        Italic
    </div>
    <div id="editor" contentEditable="true">
        Editor
    </div>
    <script>
        function executeAction(actionName) {
            console.log(actionName);
            var sup = document.queryCommandSupported(actionName);
            console.log(sup);
            var res = document.execCommand(actionName, false, "");
            console.log(res);
        }
    </script>
</body>
</html>

所以这是有趣的部分:请注意 boldbuttonitalicdiv。可以在控制台日志中检查或通过更改其中一个操作来支持这两个命令,因此这是唯一的区别。然而,按钮做了它应该做的事情(它将"editor"中的选定文本更改为粗体)而div 没有。

控制台日志显示 execCommanddiv returns false 执行,根据文档,实际上是一条非常详细的错误消息,上面写着 "something went wrong and we couldn't be bothered to tell you more".

遗憾的是,即使我获得了所有信息,我也无法弄清楚为什么这些元素的行为会有所不同。其中一个事件实际上是异步执行的吗?按钮是否获得其他元素必须首先请求的特殊权限?编辑 API 是否检查它的执行位置以确保有 "good" UI?

在这两种情况下,函数都能正确执行。我认为这可能会发生:

  1. 当您单击 button 时,所选文本不会丢失,因此会应用效果。
  2. 当您单击 div 时,在函数调用之前选择会丢失,因此不会应用效果。