我希望在选择某些文本后出现一个类似气泡的工具提示。它确实有效,但是当您向下滚动并在文档末尾附近尝试它时(如果它很长),它就不起作用了。这是相当随机的。有时,工具提示出现在文档开头附近,或者它可能出现在太左或太右的位置,或者可能只出现一部分,或者根本不出现。
这是小提琴: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();
}
});