をリセットし、それがされて何をするか、それが機能を使用している場合、任意のテキストが選択されていることを確認し私は下記のようなJavaScriptを持つ変数のonclickイベント
doSomethingWithSelectedText
機能(呼び出しますgetSelectedObj)。
getSelectedObjはオブジェクトを返します。
問題は、一部のテキストが選択されるたびにdiv #textが更新されるという問題です。そしてdiv #searchは、強調表示された/選択されたテキストを検索する新しいGoogleタブを開きます。
それ以外の選択では、それ以降は更新が停止します。
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
function getSelectedObj() {
var selObj = {};
selObj.text = '';
if (typeof window.getSelection != "undefined") {
selObj.rect = window.getSelection().getRangeAt(0).getBoundingClientRect() ;
selObj.text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
// this block not used in new versions of chrome, mozilla and IE11
selObj.text = document.selection.createRange().text;
}
return selObj;
}
function doSomethingWithSelectedText(e) {
var selectedObj = getSelectedObj();
if (selectedObj.text) {
document.querySelector('#popup').style.display = 'block';
document.querySelector('#popup').style.top = e.clientY - 40;
document.querySelector('#popup').style.left = e.clientX + 20;
document.querySelector('#text').innerHTML = selectedObj.text;
document.querySelector('#search').addEventListener('click', function (e) {
window.open('https://www.google.com/search?q=' + selectedObj.text);
});
}
else {
document.querySelector('#popup').style.display = 'none';
selectedObj.text = '';
}
}
addEventListenerがmouseupイベントのif()の内部で定義されている可能性があります。それは更新されません。私はこれをどう扱うべきか分からない。あなたが本当にとして、あなたの関数の外のイベントハンドラを置くべき
index.htmlを
<div id="popup">
<div id ="text"></div>
<div id="search" class="fa fa-search"></div>
<div id="save" class="fa fa-file"></div>
</div>
Styles.cssを
#popup{
display: none;
background-color: orange;
color: white;
position: absolute;
z-index: 1000;
width:100px;
height: 50px;
}
#search,#save {
display: inline-block;
padding: 15px;
font-size: 20px;
}
この回答はお役に立ちましたか?あなたはコメントを残すことができますか? – trincot