日本語入力確定を判定するImeCheckerクラスと併用して使用するのが望まれる。
Last active
November 14, 2017 15:20
-
-
Save sainu/127ebf7281e17f6da69035b9d9bef33d to your computer and use it in GitHub Desktop.
contenteditableの最初の行をタグでラップさせる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="editable" contenteditable="true" placeholder="入力..."></div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#editable { | |
background-color: #eee; | |
padding: 1rem; | |
} | |
#editable[contenteditable=true]:empty:before { | |
content: attr(placeholder); | |
color: #999; | |
display: block; /* For Firefox */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
class化