マウスアップが発生するまでwindow.getSelection()
が空であるようです。私はクリックされた単語を取得してマウスアップで選択することができますが、マウスアップが発生する前にmousedownでこれを行う必要があります。以下のjsfiddleの例では、マウスを起動しています(正常に起動しました)が、物理的なマウスアップが発生するまでテキストの選択はまだ空です。マウスがダウンしている間にテキスト選択をトリガします(mouseupまでwindow.getSelection()が空です)
https://jsfiddle.net/aoznge7j/1/
$(function() {
app_init();
});
function app_init() {
container = $('div');
selection = false;
word = false;
start = false;
end = false;
if(window.getSelection) {
selection = window.getSelection();
selection.empty();
} else {
alert('Please update your browser to use this application.');
}
container.mousedown(function(e) {
console.log('mousedown');
mouse_press(e);
});
container.mouseup(function(e) {
console.log('mouseup');
mouse_release(e);
});
}
function mouse_press(e) {
$(e.target).trigger('mouseup'); // this triggers the mouseup but selection is empty
}
function mouse_release(e) {
handle_selection(); //physical mouseup works
}
function handle_selection() {
selection = window.getSelection();
//console.log(selection);
if(selection.isCollapsed) {
// this is how i am selecting the clicked word, and yes i know .modify is non-standard
selection.modify('move', 'forward', 'character');
selection.modify('move', 'backward', 'word');
selection.modify('extend', 'forward', 'word');
word = selection.toString();
start = selection.anchorOffset;
end = selection.focusOffset;
console.log('word:'+word+' start:'+start+' end:'+end);
}
}
テキスト選択を(これが真isCollapsed)マウスがまだダウンしている間にトリガする別の方法はありますか?
ありがとうございます。以前は選択されていたものではなく、現在クリックされているもの(mousedowned)を取得する必要があります。 –
イベントをmousemoveに変更しました。これで、マウスをドラッグしている間に強調表示されているテキストがキャプチャされます。それがあなたのために働くかどうか私に教えてください。 –
もう一度ありがとうございます。これは私の後ろのものに非常に近いですが、実際にマウスの動きに頼らずに単語を選択する必要があります。それだけでマウスを動かした後にトリガーするには何らかの方法が必要ですか? –