【问题标题】:Get Selected Text In ContentEditable DIV?在 ContentEditable DIV 中获取选定的文本?
【发布时间】:2013-08-28 09:49:17
【问题描述】:

所以我的 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 执行该函数?我只希望它在突出显示实际文本时执行。

【问题讨论】:

    标签: javascript jquery html contenteditable


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      灵感来自@Tarun Dugar。但不适用于所有浏览器。以下工作。

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

      【讨论】:

        【解决方案3】:

        试试这个

        window.getSelection().anchorNode.data.substring( window.getSelection().anchorOffset,window.getSelection().extentOffset )
        

        尝试工作示例Here

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            【解决方案5】:

            当用户开始选择时会触发“selectstart”事件。没有选择结束事件,但您可以在“selectstart”事件触发后监听 mouseup 事件以确保选择已经发生。

            编辑:

            检查 - HTML Content Editable div: select text event

            【讨论】:

              【解决方案6】:

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

              【讨论】:

                猜你喜欢
                • 2011-03-08
                • 1970-01-01
                • 2011-04-29
                • 1970-01-01
                • 1970-01-01
                • 2011-03-28
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多