【问题标题】:How to check if a line inside contenteditable div is empty如何检查contenteditable div内的一行是否为空
【发布时间】:2016-12-28 08:19:50
【问题描述】:

如何更改此代码,以便它检测 contenteditable div 中的一行是否为空有文本?

$('#area').on("keyup change", function() {
    if( this.value.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
     && this.value.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
        console.log("empty");
    } else {
        console.log("has stuff");
    }
});

使用 textarea.我试图用 innerHTML 替换 VALUE - 唉!没有运气。

http://jsfiddle.net/5uZjV/1/

更新:我正在寻找的是找出 A SEPARATE LINE 是否为空。例如 - 尝试添加几行,然后使用退格删除任何一行。逐个删除一个符号 - 当行上没有更多符号时 - 脚本应返回“空”。示例:

  1. 第一行文本 // 在“Del”/“Backspace”键上返回“有东西”
  2. //在“Del”/“Backspace”键上返回“空”
  3. 第三行文本 // 在“Del”/“Backspace”键上返回“有东西”

【问题讨论】:

    标签: jquery dom contenteditable


    【解决方案1】:

    您需要将 .value 更改为 .textContent。

    $('#area').on("keyup change", function() {
       if( this.textContent.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
     && this.textContent.substr(this.selectionStart).match(/^(?:\s+|$)/)){
        console.log("empty");
        } else {
        console.log("has stuff");
       }
    });
    

    如果我理解正确,请将 textarea 更改为 div。

    <div name="" id="area" cols="30" rows="10" contenteditable=true></div>
    

    【讨论】:

    • 感谢 Ekim!虽然这并不能完成所有功能。请看一下:jsfiddle.net/5uZjV/3 问题是 - 它现在检测整个 DIV 是否为空,但我正在寻找的是找出 A SEPARATE LINE 是否为空。例如 - 尝试使用退格键删除第三行。逐个删除一个符号 - 当行上没有更多符号时 - 脚本应返回“空”
    【解决方案2】:

    使用您的代码(添加 mouseover 以在鼠标悬停时获取 div 状态)使用 innerHTML:

    $('#area').on("keyup change mouseover", function() {
       if( this.innerHTML.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
     && this.innerHTML.substr(this.selectionStart).match(/^(?:\s+|$)/)){
        console.log("empty");
        } else {
        console.log("has stuff");
       }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div name="" id="area" style="width:100px;height:100px;border:1px solid black;" contenteditable=true></div>

    使用mouseover 并使用innerHTML 获取数据。

    $('#area').mouseover( function() {
        if( this.innerHTML.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
         && this.innerHTML.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
            console.log("empty");
        } else {
            console.log("has stuff");
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div name="" id="area" style="width:100px;height:100px;border:1px solid black;" contenteditable=true></div>

    【讨论】:

    • 谢谢!问题是 - 您的脚本现在检测整个 DIV 是否为空,但我正在寻找的是找出 A SEPARATE LINE 是否为空。例如 - 尝试添加几行,然后使用退格删除任何一行。逐个删除一个符号 - 当行上没有更多符号时 - 脚本应返回“空”
    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 2013-01-10
    • 2021-08-16
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多