jQuery:如何将函数绑定到mouseup事件之后立即发生的某个事件

jQuery: how do I bind a function to some event that occurs immediately after the mouseup event?

本文关键字:事件 之后 mouseup 函数 绑定 jQuery      更新时间:2023-09-26

我想在选择文本后立即调用一个函数。我目前在mouseup上调用了一个函数,但这仍然是在选择完成之前。

那么,如何在做出选择后立即调用函数呢?

EDIT:文本字段有一个.select(),但我正在DOM中的任何地方寻找选择,主要是span和div等。

您尝试过select事件吗?如果jQuery在你的应用程序中可用,你可以这样做:

$("#someElement").select(function(e) {
    // do something!
})

对于常规文本(即不是输入),下面@mrtherman的建议应该有效:

$( document ).bind( "mouseup", function(e) {
    var text = getSelected();
    if ( text ) {
        // do something with the selected text
    }
});
function getSelected() {
    if ( window.getSelection ) {
        return window.getSelection();
    } else if ( document.getSelection ) {
        return document.getSelection();
    } else {
        var selection = document.selection && document.selection.createRange();
        if ( selection.text ) {
            return selection.text;
        }
        return false;
    }
    return false;
};

希望能有所帮助!干杯