Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript contenteditable div*的window.getSelection()单击*_Javascript_Html_Contenteditable_Getselection - Fatal编程技术网

Javascript contenteditable div*的window.getSelection()单击*

Javascript contenteditable div*的window.getSelection()单击*,javascript,html,contenteditable,getselection,Javascript,Html,Contenteditable,Getselection,我有一个contenteditable div,希望在用户单击span时获得用户的选择 我的问题是,当我单击span时,选择被取消选中,因此窗口。getSelection().toString()返回' 单击span的,如何使其工作 我知道实际的getSelection()是有效的,因为如果我在setTimeout的5秒钟内包装window.getSelection().toString(),5秒钟后,我会得到所选的文本 我的代码: $('#btn')。单击(函数(){ console.log

我有一个contenteditable div,希望在用户单击
span
时获得用户的选择

我的问题是,当我单击
span
时,选择被取消选中,因此
窗口。getSelection().toString()
返回
'

单击
span
,如何使其工作

我知道实际的
getSelection()
是有效的,因为如果我在
setTimeout
的5秒钟内包装
window.getSelection().toString()
,5秒钟后,我会得到所选的文本

我的代码:

$('#btn')。单击(函数(){
console.log(window.getSelection().toString());//返回“”
});
#btn{
光标:指针;
}

获得选择权



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

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

document.getElementById('btn').onclick = function(){
  console.log(selection);
};
或者,如果您有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);
});

您可以在单击contenteditable div时存储所选内容,然后在单击按钮时返回所选内容

document.querySelector("#ce").addEventListener(function(){
  userSelection= window.getSelection().toString();
});


document.querySelector("#btn").addEventListener("mouseup",function(){

  document.querySelector("#selection").innerHTML= 
    "You have selected:<br/><span class='selection'>" +  userSelection +"</span>";

});
document.querySelector(“#ce”).addEventListener(函数(){
userSelection=window.getSelection().toString();
});
document.querySelector(“#btn”).addEventListener(“mouseup”,function(){
document.querySelector(“#selection”).innerHTML=
“您已选择:
“+userSelection+”; });

用鼠标在div id=“ce”上方获取选择文本