テキストを選択した後、マウスが置かれている場所に吹き出しのようなツールチップを表示したいと思います。そして、それは機能しますが、下にスクロールしてドキュメントの終わり近くで試してみると(長い場合)、機能しません。それはかなりランダムです。ツールチップがドキュメントの先頭近くに表示されたり、左または右に遠すぎたり、一部しか表示されなかったり、まったく表示されなかったりする場合があります。
これがフィドルです:http://jsfiddle.net/bdAbZ/
コードは次のとおりです。
// Generate the speech bubble
// Temporary placeholder
var $speechBubble = $('<p class="speech-bubble"></p>');
$speechBubble.appendTo('body');
var mousePosition;
function updateMousePosition(event) {
/* Update the global variable mousePosition with the current location of the mouse.
*/
mousePosition = {left: event.pageX, top: event.pageY};
}
$(document).mousemove(updateMousePosition); // mousePosition will always be up-to-date.
function getSelectedText() {
/* Return the text that the user has selected.
**
** If he hasn't selected anything, return an empty string.
*/
// Different browsers, different ways of getting the selected text.
if (window.getSelection) {
return window.getSelection();
}
else if (document.getSelection) {
return document.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
else {
// This should normally never happen.
alert('Could not get the selected text.')
return false;
}
}
$('p').mouseup(function() {
/* Check if the user has selected any text within the p area.
**
** If he has, show the speech bubble menu.
*/
var selectedText = getSelectedText();
if (selectedText != '') {
$speechBubble.text(selectedText);
$speechBubble.offset(mousePosition);
$speechBubble.show();
}
});
$(document).mouseup(function() {
/* Check if no text has been selected.
**
** If no text has been selected, hide the speech bubble menu.
**
** Why? The user would probably try to get rid of the speech bubble by clicking somewhere else.
*/
if (getSelectedText() == '') {
$speechBubble.hide();
}
});