【问题标题】:Display popup above highlighted text in contenteditable div?在 contenteditable div 中突出显示的文本上方显示弹出窗口?
【发布时间】:2018-10-05 23:25:54
【问题描述】:

我正在我的一个应用程序中构建一个简单的博客式功能,并使用 HTML5 contenteditable 属性,因为它很干净。但是,我现在需要做的是,当用户突出显示 contenteditable div 中的某些文本时,需要在其上方出现一个弹出窗口。现在我有一个函数可以获取选定的文本,该文本绑定到 DIV 的 mouseup()。但是,当我单击 contenteditable 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 时,如何防止调用被触发,并且仅在他们突出显示某些文本时触发?

【问题讨论】:

  • 那么你的代码做错了什么?

标签: javascript jquery css html


【解决方案1】:
$("#content-create-partial").bind("mouseup", function(){
 if (document.getSelection) {
                var text = getSelected();
                if(text) {
                    console.log(text);
                }
                else{
                    console.log("Nothing selected?");
                }


  } 
         });

【讨论】:

    【解决方案2】:

    将其转换为字符串 (.toString()),如果所选字符串为空,请使用 trim(),并在 mouseup 事件中检查所选字符串的长度。

     $("#content-create-partial").bind("mouseup", function(){
            var text = getSelected().toString().trim();
            if(text.length>0) {
                console.log(text);
            }
            else{
                console.log("Nothing selected?");
            };
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多