クライアント側でJavaScriptを使用してInternetExplorerアクセラレータのようなものを作成できますか?
ユーザーがページ上のテキストを選択したときにクリック可能なアイコンを表示したい。
待つべきイベントは何ですか?
クライアント側でJavaScriptを使用してInternetExplorerアクセラレータのようなものを作成できますか?
ユーザーがページ上のテキストを選択したときにクリック可能なアイコンを表示したい。
待つべきイベントは何ですか?
本質的には、document.onmouseup
イベントを適切に処理し、非表示の「アクセラレータ」div
を表示して、選択したテキストを取得するという考え方です。
次のサンプルがあなたにとって良い出発点になると思います:
<html>
<head>
<script>
function getSelectedText() {
var selection = '';
if (window.getSelection) selection = window.getSelection().toString();
else if (document.getSelection) selection = document.getSelection();
else if (document.selection) selection = document.selection.createRange().text;
return selection;
}
function showAccelerator(x, y){
var text = getSelectedText();
if (text !== ''){
accelerator.style.display = '';
accelerator.style.left = x;
accelerator.style.top = y;
timeout_id = setTimeout(hideAccelerator, 1000);
} else {
hideAccelerator()
}
}
function hideAccelerator(){
clearTimeout(timeout_id);
accelerator.style.display='none';
}
function isAcceleratorHidden(){
return accelerator.style.display === 'none';
}
function onMouseUp(evt){
if (isAcceleratorHidden()){
var event2 = (document.all) ? window.event : evt;
showAccelerator(event2.clientX, event2.clientY);
}
}
function alertSelection(){
alert(getSelectedText());
}
document.onmouseup = onMouseUp;
</script>
</head>
<body>
<div id="accelerator" style="position: absolute; width: 100px; left: 0px; top: -50px; display: none; border: solid; background-color : #ccc;">
accelerator div<input type="button" value="alert" onclick="alertSelection();" />
</div>
<p>
sometext<br/><br/><br/>
even more text
</p>
</body>
</html>
おそらく最良の方法は、次のような選択をテストする関数を呼び出すページにマウスアップリスナーを設定することです。
function hasSelection() {
var selText = "";
if (document.selection) { // IE
selText = document.selection.createRange().text;
} else () { // Standards-based browsers
selText = document.getSelection();
}
// This simple example does not include legacy browsers like Netscape 4, etc.
if (selText !== "") {
return true
}
return false;
}
これを変更して、選択範囲を返し、他の方法で操作することができます。ただし、ここで返されるブール値によって、ボタンが表示されるかどうかが決まる可能性があります。
IEの場合はattachEventを使用し、Firefoxなどの場合はaddEventListenerを使用します。al、およびmouseupイベントをリッスンします。