选择所有文本时,execCommand bold在Firefox中失败

时间:2013-09-14 22:39:12

标签: javascript firefox wysiwyg contenteditable execcommand

我正在设置使用JavaScript进行一些简单的WYSIWYG编辑,我在Firefox中遇到了一个问题,我没有在Chrome或IE(最近版本的所有版本)中获得。选中contentEditable范围内的所有文字后,如果我尝试使用document.execCommand('bold',false,null)将其设为粗体,则会收到相当不明确的错误消息:“NS_ERROR_FAILURE:失败”

以下是一些简单的示例代码,可以轻松地重现该问题:

<html>
    <head>
        <script>
            function start(){

                var edit = document.getElementById('edit');
                edit.contentEditable = true;

                var button = document.getElementById('button');
                button.onclick = function(){

                    // Get the editable span
                    var edit = document.getElementById('edit');

                    // Select the contents of the span
                    var range = document.createRange();
                    range.selectNodeContents(edit);
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // Make the text bold
                    document.execCommand('bold',false,null);

                }

            }
        </script>
    </head>
    <body onload="start();">
        <span id='edit'>Click on the button</span>
        <button id='button'>Bold It All!</button>
    </body>
</html>

那么,我在这里做错了什么?我刚碰到一个bug吗?如果是这样,有人可以建议一个解决方案吗?

1 个答案:

答案 0 :(得分:2)

这是一个错误。考虑filing it。简而言之:

  • 编辑器将尝试用<span>(或<b>时的其他<span>包裹useCSS
  • 这会删除<span>
  • 因此<span>的父级代码contenteditable="true"是可编辑的,而不是。{/ li>
  • 轰!

解决方法:<div>一个真正的块元素,如{{1}}。

相关问题