window.getSelection() for contenteditable div *点击*

ᔕᖺᘎ*_*ᖺᘎᕊ 7 html javascript contenteditable getselection

我有一个 contenteditable div 并希望在用户单击span.

我的问题是,当我单击 时span,选择未选中,因此window.getSelection().toString()返回''

我怎样才能在点击a 时span让它工作?

我知道实际的getSelection()作品,因为如果我window.getSelection().toString()setTimeout5 秒内换行,5 秒后,我会得到选定的文本!

我的代码:

$('#btn').click(function() {
  console.log(window.getSelection().toString()); //returns ''
});
Run Code Online (Sandbox Code Playgroud)
#btn {
  cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='btn'>get selection</span>
<br><br>
<div id='ce' contenteditable='true'>test</div>
Run Code Online (Sandbox Code Playgroud)

小智 1

由于没有可用于专门检测“选择”或“取消选择”的事件,因此您必须侦听事件mouseup并填充可以将选择存储在内存中的“缓存变量”:

var selection = '';
document.getElementById('ce').onmouseup = function(){
  selection = window.getSelection().toString();
};

document.getElementById('btn').onclick = function(){
  console.log(selection);
};
Run Code Online (Sandbox Code Playgroud)

或者,如果你有 jQuery,你可以尝试这个更抱怨的版本,这也考虑了基于键盘的选择:

var selection = '', shifted = false;
$('#ce').on('mouseup keyup keydown', function(e){
  if (e.type === 'keydown') {
    shifted = e.shiftKey;
    return;
  }

  if (
    e.type === 'mouseup' ||
    (shifted && (e.keyCode === 39 || 37 || 38 || 40))
  ){
    selection = window.getSelection().toString();
  }
});

$('#btn').on('click', function(){
  console.log(selection);
});
Run Code Online (Sandbox Code Playgroud)