Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - End of text selection event?

Is there an event for the end of text selection on iOS?

I know I can run an event when the selection changes through the following:

document.addEventListener("selectionchange", function(event) {
        var text = window.getSelection().toString();
        $(".output").append("<div>" + text + "</div>");
}, false);

<div class="output"></div>

This will update .output with the selected text, but runs every time the selection changes. What I would want, is to only capture the text after the selection has finished.

Is there any such event? Is it possible to do something like this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Similar to you i didn't found a good solution for this problem, So i decided to create a workaround. it's not the prettiest but it works.

I created a timeout function and bind it to a "onselectionchange" event. Each time the event fired i check if my timeout is running, and if so i delete it and create a new one.

when the timeout is finished a custom event "selectionEnd" is fired.

// bind selection change event to my function
document.onselectionchange = userSelectionChanged;

function userSelectionChanged() {

    // wait 500 ms after the last selection change event
    if (selectionEndTimeout) {
        clearTimeout(selectionEndTimeout);
    }

    selectionEndTimeout = setTimeout(function () {
        $(window).trigger('selectionEnd');
    }, 500);
}

$(window).bind('selectionEnd', function () {

    // reset selection timeout
    selectionEndTimeout = null;

    // TODO: Do your cool stuff here........

    // get user selection
    var selectedText = getSelectionText();

    // if the selection is not empty show it :)
    if(selectedText != ''){
       // TODO: Do something with the text
    }
});

DEMO: http://jsfiddle.net/dimshik/z8Jge/

I wrote a small post about it in my blog: http://www.dimshik.com/end-of-text-selection-event-on-ios-workaround/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...