如何检查contenteditable div中的行是否为空

时间:2016-12-28 08:19:50

标签: jquery dom contenteditable

如何更改此代码,以便检测c ontenteditable 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" /"退格" keyup返回"有东西"
  2. // on" Del" /" Backspace" keyup返回"空"
  3. 第三行文字// on" Del" /" Backspace" keyup返回"有东西"

2 个答案:

答案 0 :(得分:2)

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

$('#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>

答案 1 :(得分:2)

您需要将.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>
相关问题