2

テキストを選択した後、マウスが置かれている場所に吹き出しのようなツールチップを表示したいと思います。そして、それは機能しますが、下にスクロールしてドキュメントの終わり近くで試してみると(長い場合)、機能しません。それはかなりランダムです。ツールチップがドキュメントの先頭近くに表示されたり、左または右に遠すぎたり、一部しか表示されなかったり、まったく表示されなかったりする場合があります。

これがフィドルです: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();
    }
});
4

2 に答える 2

1

私はここでフィドルを作りました:http://jsfiddle.net/bdAbZ/8/

バブルは絶対に配置されています。また、マウスアップのカーソルに合​​わせて吹き出しを中央に配置しました。

これがあなたのために働くかどうか私に知らせてください...

更新:大量のメモリを消費する可能性があるため、mousemoveリスナーを削除したなどのいくつかの更新を行いました。mouseupイベントが発生するまで、カーソル位置を更新する必要はありません。また、マウスアップリスナーを段落に適切に委任しました。これはすべて、表示していないコードを中断しないことを前提としています:http: //jsfiddle.net/bdAbZ/9/

于 2012-10-15T19:07:03.297 に答える
0

これはどう?

http://jsfiddle.net/bdAbZ/5/

マウスアップイベントでマウス位置を取得できるのに、なぜマウス移動でマウス位置を追跡しているのかわかりません。また、ふきだしのクラスを絶対に配置しました。

編集:それでもそれを台無しにする1つのことは、単語をダブルクリックして選択した場合です。

于 2012-10-15T18:27:50.417 に答える