在 Firefox 中从内容可编辑 div 获取范围不起作用

Getting range from content editable div in Firefox does not work

在我们的项目中,我们有一个内容可编辑 div 和另一个 div 用作显示一些选项的按钮。用户选择这些选项之一,然后将值插入到内容可编辑 div 的插入符处。所以我试图从可编辑的内容中获取选定的范围值 div 以在插入符号处插入值文本。

我在可编辑内容 div 上使用 blur() 事件实现了它,以便在失去焦点之前获得选择,保存该范围数据并将其用于 div 单击事件。在 Chrome/Edge 中工作正常,但在 Firefox/Safari 中却不行。

我不明白的是,当使用输入按钮时,它适用于所有浏览器,但是当使用 div 作为按钮时,它在 Firefox/Safari 中不起作用。

JSFiddle:https://jsfiddle.net/v7secq04/4/

代码:

HTML

<!-- input button and div used as button -->
<input type="button" id="selection-button" value="Get selection">
<div id="selection-div"  style="border-style: solid; width: 100px;cursor: pointer;">Selection DIV</div>

<!-- editable div -->
<div id="editor" contenteditable="true" style="border-style: solid; height: 150px;">Please select some text.</div>

<!-- inputs to display the range values -->
Range start: <input id="start" type="text"/><br/>
Range end:  <input id="end" type="text"/>

JS

var start = 0,
end = 0;

// On clicking on the button or the div, the editor div blur event is triggered.
// We get the range start and end, and store them.
$( "#editor" ).blur(function() {
  var range = window.getSelection().getRangeAt(0);
  var preSelectionRange = range.cloneRange();
  preSelectionRange.selectNodeContents(editor);
  preSelectionRange.setEnd(range.startContainer, range.startOffset);
  start = preSelectionRange.toString().length;
  end = start + range.toString().length;
});

// After the blur event is finished, the click event is triggered.
// Start and end values are displayed in the inputs
$('#selection-button, #selection-div').on('click', function() {
  $('#start').val(start);
  $('#end').val(end);
  start = 0;
  end = 0;
});

要复制它:

有人知道为什么吗?有什么方法可以使用 div 按钮获取正确的范围数据?

谢谢!

我通过将事件侦听器拆分为按钮和 div 来实现它的工作。

<script type="text/javascript">
var start = 0,
    end = 0;

$(() => {
    $('#selection-div').on('mousedown', getSelection);
    $('#selection-button').on('click', getSelection);

    function getSelection() {
        var range = window.getSelection().getRangeAt(0);
        var preSelectionRange = range.cloneRange();
        preSelectionRange.selectNodeContents(document.getElementById('editor'));
        preSelectionRange.setEnd(range.startContainer, range.startOffset);
        start = preSelectionRange.toString().length;
        end = start + range.toString().length;

        $('#start').val(start);
        $('#end').val(end);
        // Not needed, as you would override it on every click
        //start = 0;
        //end = 0;
    }
})
</script>