window.getSelection()用于contenteditable div * on click * [英] window.getSelection() for contenteditable div *on click*
问题描述
我有一个contenteditable div,并希望在点击 span
时获得用户的选择。
我的问题是,当我点击 span
时,选择被取消选择,所以 window.getSelection()。toString()
返回'
。
如何在点击点击 code> span ?
我知道实际的 getSelection()
,因为如果我在5秒内在 setTimeout
中包装 window.getSelection()。toString()
,5秒后,我得到了选定的文本!
我的代码:
$('#snippet-code-js lang-js prettyprint- btn')。click(function(){console.log(window.getSelection()。toString()); //返回''});
#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>< ;
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'||
(shift&&(e .keyCode === 39 || 37 || 38 || 40))
){
selection = window.getSelection()。toString();
}
}) ; ('click',function(){
console.log(选择);
});
$('#btn')。
I have a contenteditable div and want to get the user's selection when they click a span
.
My problem is that when I click the span
, the selection gets unselected so window.getSelection().toString()
returns ''
.
How can I get this to work on click of a span
?
I know the actual getSelection()
works, because if I wrap window.getSelection().toString()
in a setTimeout
of 5 seconds, after 5 seconds, I get the selected text!
My code:
$('#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>
解决方案 Since there is no event you can use to specifically detect a 'select' or 'deselect', you'll have to listen to a mouseup
event and populate a "cache variable" that can store the selection in the memory:
var selection = '';
document.getElementById('ce').onmouseup = function(){
selection = window.getSelection().toString();
};
document.getElementById('btn').onclick = function(){
console.log(selection);
};
Or, provided you have jQuery, you could try this more complaint version, which also factors in keyboard-based selections:
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);
});
这篇关于window.getSelection()用于contenteditable div * on click *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文