开发者

How do I determine, cross browser, if the node within a contenteditable element is empty?

开发者 https://www.devze.com 2023-01-23 08:15 出处:网络
Without having to resort to a library, I would like to know if (not when) the content of the contenteditable element below has been deleted.

Without having to resort to a library, I would like to know if (not when) the content of the contenteditable element below has been deleted.

<span contenteditable id=foo>tell me when this string is d开发者_如何学JAVAeleted</span>


Unfortunately, I run Linux so I can't test IE, but it works in Chrome and Firefox

document.getElementById("foo").onkeyup = function (event) {
    // Firefox doesn't like innerText
    var content = this.innerText || this.innerHTML;

    // this replace strips whitespace (can be removed if needed)
    if (content.replace(/\s/g, "").length === 0) {
        this.blur(); // when using an alert, the onkeyup event will fire again if you hit enter...
                     // this removes the focus beforehand
                     // (can be removed if you are not using an alert box or something similar)

        alert("content deleted");
    }
};


There is no onchange event, but there is an onkeyup event:

document.getElementById('foo').onkeyup = function(){
  if(this.innerHTML.length == 0) alert('string deleted');
};


The only way I can think of at the moment is to create a polling event that checks every little bit to see if the div still contains the same text. If you know what text you're looking for, you could just use some regex (or plain string searching) to see if the string is still there.

You could listen for keydown, keypress, or keyup events, but remember to add a timeout to make sure that their last keypress has been taken into consideration, as their last press may have been the backspace key.


var empty=document.getElementById("foo").innerHTML.replace(/<[^>]*>/g,"").replace(/ /g,"").length==0;
0

精彩评论

暂无评论...
验证码 换一张
取 消