Placeholder for contenteditable div

后端 未结 12 1581
栀梦
栀梦 2020-12-12 23:18

I have the following: FIDDLE

The placeholder works fine and dandy until you type something, ctrl + A, and delete. If you do that, th

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 00:07

    It feels like I am repeating myself, but why not to check contenteditable element mutations? Trying to bind everything to event that are changing content are pain in the butt. What if You need to add button (For example paste), or change content dynamically (javascript). My approach would be using MutationObservers. Demo fiddle

    HTML:

    CSS:

    .test {
        width: 500px;
        height: 70px;
        background: #f5f5f5;
        border: 1px solid #ffffd;
        padding: 5px;
    }
    
    .test[placeholder]:empty:before {
        content: attr(placeholder);
        color: #555; 
    }
    

    JavaScript:

    var target = document.querySelector('#test');
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
          if (target.textContent == '') {
              target.innerHTML = '';
          }
      });    
    });
    var config = { attributes: true, childList: true, characterData: true };
    observer.observe(target, config);
    

提交回复
热议问题