Skip to content

Instantly share code, notes, and snippets.

@sainu
Last active November 14, 2017 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sainu/127ebf7281e17f6da69035b9d9bef33d to your computer and use it in GitHub Desktop.
Save sainu/127ebf7281e17f6da69035b9d9bef33d to your computer and use it in GitHub Desktop.
contenteditableの最初の行をタグでラップさせる
<div id="editable" contenteditable="true" placeholder="入力..."></div>
let editable = document.getElementById('editable');
function wrapWithPTag(node) {
// contenteditableの最初の要素がpタグで囲まれてないのでpタグでラップする
let firstLine = node.firstChild;
if (!!firstLine && firstLine.tagName != 'P') {
let p = document.createElement('p');
p.append(firstLine);
node.prepend(p);
}
}
editable.onkeyup = function(e) {
if (e.keyCode === 13) {
wrapWithPTag(e.target);
// 改行した時に生成されるタグをpタグにする
document.execCommand('formatBlock', false, 'p');
}
}
editable.onblur = function(e) {
wrapWithPTag(e.target);
}
#editable {
background-color: #eee;
padding: 1rem;
}
#editable[contenteditable=true]:empty:before {
content: attr(placeholder);
color: #999;
display: block; /* For Firefox */
}
@sainu
Copy link
Author

sainu commented Nov 14, 2017

class化

export default class FormatInsideOfContenteditable {
  static wrapFirstLineWithTag(node, tagName) {
    let firstLine = node.firstChild;
    return new Promise(resolve => {
      if (!!firstLine && firstLine.tagName != 'P') {
        let tag = document.createElement(tagName);
        tag.append(firstLine);
        node.prepend(tag);
        resolve(node);
      }
    });
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment