在ContentEditable DIV中获取所选文本?

Tom*_*ell 10 html javascript jquery html5 contenteditable

所以我在我的Rails应用程序中有一个可信的div,并且需要能够在突出显示时在文本上方显示一个小弹出窗口.目前我的代码有效,并在警报中显示突出显示的文本.但是,该函数在mouseup上执行,因此当您单击div开始键入或突出显示时,它会抛出一个空警报.

这是我的代码:

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;
        };
$("#content-create-partial").bind("mouseup", function(){
                var text = getSelected();
                if(text) {
                    console.log(text);
                }
                else{
                    console.log("Nothing selected?");
                };
            });
Run Code Online (Sandbox Code Playgroud)

当用户点击contentEditable div时,如何防止jQuery执行该函数?我只希望它在突出显示实际文本时执行.

Tar*_*gar 5

您可以比较window.getSelection().anchorOffsetwindow.getSelection().extentOffset查看它们是否相等。如果是,那么这只是一次普通的点击。


Men*_*ndy 5

您可以简单地检查该Selection.toString()方法是否返回空字符串

if(window.getSelection().toString()){
    // do something
}
Run Code Online (Sandbox Code Playgroud)


Tra*_*ama 5

尝试这个

window.getSelection().anchorNode.data.substring( window.getSelection().anchorOffset,window.getSelection().extentOffset )
Run Code Online (Sandbox Code Playgroud)

在这里尝试工作示例。


ham*_*ett -2

只需检查选择是否为空:if ($.trim( text) != '') ...