Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否在ContentEditable DIV中获取所选文本?_Javascript_Jquery_Html_Contenteditable - Fatal编程技术网

Javascript 是否在ContentEditable DIV中获取所选文本?

Javascript 是否在ContentEditable DIV中获取所选文本?,javascript,jquery,html,contenteditable,Javascript,Jquery,Html,Contenteditable,因此,我在Rails应用程序中有一个contenteditable div,需要能够在突出显示文本时在文本上方显示一个小弹出窗口。目前,我有代码可以工作,它在警报中显示突出显示的文本。但是,该函数在mouseup上执行,因此当您单击div开始键入或突出显示时,它会抛出一个空警报 这是我的密码: function getSelected() { if (window.getSelection) { return window.getSelec

因此,我在Rails应用程序中有一个contenteditable 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?");
                };
            });

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

只需检查选择是否为空:
如果($.trim(text)!='')。
当用户开始选择时会触发“selectstart”事件。没有选择结束事件,但您可以在触发“selectstart”事件后侦听mouseup事件,以确保选择已发生

编辑:


选中-

您可以比较
window.getSelection().anchorOffset
window.getSelection().extendtoffset
以查看它们是否相等。如果是,则只是正常单击。

如果未选择任何内容,则以下内容将返回true

灵感来源于@Tarun Dugar。但并非在所有浏览器中都有效。以下措施奏效了

window.getSelection().focusOffset == window.getSelection().anchorOffset;

您只需检查
Selection.toString()
方法是否返回空字符串

if(window.getSelection().toString()){
    // do something
}
试试这个

window.getSelection().anchorNode.data.substring( window.getSelection().anchorOffset,window.getSelection().extentOffset )
试着在枫树下工作