سؤال

I'm using the new Firepad realtime text collaboration service.

I would like to use the JavaScript getSelection method on text in the box that the user selects.

However, my code isn't working for whatever reason.

My JavaScript:

function myFunction()
{
    alert(window.getSelection());
}

HTML:

<button onclick="myFunction();">Get Selected Text in Firepad</button>

My test site

هل كانت مفيدة؟

المحلول

After looking at the plug-in it seems FirePad is using a textarea.

According to another SO post's answer it seems that textareas don't use the same selection ranges as other nodes.

The accepted answer explains it like this:

There is extra bizarreness going on with textarea nodes. If I remember correctly they behave as any other nodes when you select them in IE, but in other browsers they have an independent selection range which is exposed via the .selectionEnd and .selectionStart properties on the node.

The highest voted answer shows a solution.

The solution uses the reference to the textarea node directly and gets the selected range from there using the element's selectionEnd and selectionStart properties, similar to this:

function myFunction() {
    var e = document.getElementById('thearea');

    //Mozilla and DOM 3.0
    if ('selectionStart' in e) {
        var l = e.selectionEnd - e.selectionStart;

        var start = e.selectionStart,
            end = e.selectionEnd,
            length = l,
            text = e.value.substr(e.selectionStart, l);

        alert(text);
    }
}

DEMO - Using selectionStart and selectionEnd for textarea


I'm not sure if this is the same across all browsers these days but the above code and the additional information in the linked SO should hopefully help you in getting the desired result.

نصائح أخرى

Firepad is based on CodeMirror. Rather than grabbing the selection directly from the DOM, you should use the functions that CodeMirror exposes to do this.

Check out getSelection() here: http://codemirror.net/doc/manual.html

you can use the functions

firepad.getHtmlFromSelection();
firepad.insertTextAtCursor(textPieces);
firepad.getHtml();  
firepad.getText();
firepad.insertText(index,textPieces);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top