在 contenteditable 中取消选择后范围文本相同

Range text is same after deselect in contenteditable

我在 contenteditable 中有一个 "mouseup" 事件处理程序,用于检查文本是否已被 select 编辑。如果您在键入后突出显示文本,一切都很好,但如果您再次单击(删除 select 文本),控制台会显示 range.toString() 是相同的,尽管没有文本被 selected。

http://jsfiddle.net/xpvt214o/857876/

在 contenteditable 中输入一些内容,然后 select 它,然后再次单击(取消 select)并检查控制台。两者 console.logs 将相同。

我需要区分真正的 selection 和 deselection。如果这是正常行为,我怎样才能区分这两个事件,或者我怎样才能以不同的方式来防止这种行为?

确实,Chrome 确实在 mouseup 事件后 更改了活动选择。

您可以为此事件添加一个 hackish 超时,这可能会中断一些时间...

或者您可以使用选择 API 的 selectionchange 事件。

每次选择更改时都会触发此事件:

$(document).on('selectionchange', function() {
  console.log(getSelection().toString());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="container">Select this dummy text</div>

额外的好处是它也适用于键盘选择。

并且要获取此事件是selection还是unselection,您可以检查selection的内容是否为空,或者如果当前范围折叠:

$(document).on('selectionchange', function() {
  var isUnselect = getSelection().getRangeAt(0).collapsed;
  viewer.style.backgroundColor = isUnselect ? 'red' : 'green';
})
#viewer{
  width: 20px;
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="viewer"></div>
<div contenteditable="true" id="container">Select this dummy text</div>

请检查这是否有帮助。

$('#container').mouseup(function() {
  console.log(getSelectedText());
});

function getSelectedText() {
  if (window.getSelection) {
    return window.getSelection().toString();
  }
  return '';
}