Javascript contenteditable div*的window.getSelection()单击*
我有一个contenteditable div,希望在用户单击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
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”上方获取选择文本