文本选择事件结束

End of text selection event?

本文关键字:结束 事件 选择 文本      更新时间:2023-09-26

iOS上是否存在文本选择结束事件?

我知道当选择通过以下方式更改时,我可以运行事件:

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

这将使用所选文本更新.output,但每次更改选择时都会运行。我想要的是,只在选择完成后捕获文本。

有这样的事件吗?有可能做这样的事吗?

绑定一个mouseup事件怎么样?

JAVASCRIPT:

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

演示:http://jsfiddle.net/dirtyd77/yTMwu/66/

与您类似,我没有找到解决这个问题的好方法,所以我决定创建一个变通方法。它不是最漂亮的,但它很管用。

我创建了一个超时函数,并将其绑定到一个"onselectionchange"事件。每次触发事件时,我都会检查我的超时是否正在运行,如果是,我会删除它并创建一个新的超时。

超时结束后,将触发自定义事件"selectionEnd"。

// 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
    }
});

演示:http://jsfiddle.net/dimshik/z8Jge/

我在博客上写了一篇关于它的小帖子:http://www.dimshik.com/end-of-text-selection-event-on-ios-workaround/

我也面临这个问题,因为我还没有找到一个好的解决方案,这是我的解决方法
当用户按下移动浏览器剪贴板中的确认/后退按钮确认其选择时,它将触发selectionEnd事件。

var longpress = false;
var longpressTimer = null;
var loop = null;
var latestSelection = null;
window.ontouchstart = function(){
    longpressTimer = setTimeout(function(){
        longpress = true;
        loop = setInterval(getSelection, 200);
    }, 500)
};
window.ontouchend = function(){
    if(longpressTimer){
        clearTimeout(longpressTimer);
    }
    longpress = false;
}
var getSelection = function (){
    var s = window.getSelection();
    if(s.rangeCount > 0){
        latestSelection = s.getRangeAt(0);
    }else{
        clearInterval(loop);
        var selEndEvent = new CustomEvent("selectionEnd", {"detail": latestSelection});
        window.dispatchEvent(selEndEvent);
    }
}

当执行长按时,它会启动一个间隔来监视选择。然后用户确认他的选择,剪贴板会自动删除它;中断监视器循环并发送selectionEnd事件
您可以访问详细信息属性中最后一个选定的文本。

我希望得到一些关于这个问题的消息,并得到一个更好的解决方案。