【问题标题】:window.getSelection() for contenteditable div *on click*window.getSelection() for contenteditable div *点击*
【发布时间】:2015-11-17 04:03:34
【问题描述】:
我有一个内容可编辑的 div,并希望在用户单击 span 时获得用户的选择。
我的问题是,当我单击span 时,选择会被取消选择,因此window.getSelection().toString() 返回''。
如何在点击 span 时使其工作?
我知道实际的 getSelection() 有效,因为如果我将 window.getSelection().toString() 包裹在 5 秒的 setTimeout 中,5 秒后,我会得到选定的文本!
我的代码:
$('#btn').click(function() {
console.log(window.getSelection().toString()); //returns ''
});
#btn {
cursor: pointer;
}
<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>
【问题讨论】:
标签:
javascript
html
contenteditable
getselection
【解决方案1】:
您可以在点击您的 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>";
});
http://jsfiddle.net/xnvp38u3/
【解决方案2】:
由于没有可用于专门检测“选择”或“取消选择”的事件,您必须监听 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);
});