.editor {
width: 100%;
min-height: 100%;
height: 100%;
background-color: black;
color: #fff;
}
canvas {
background-color: green;
}
<div contenteditable><canvas></canvas></div>
How could I add canvas to contenteditable div
I have this code
<style>
.editor {
width: 100%;
min-height: 100%;
height: 100%;
background-color: black;
color: #fff;
}
canvas {
background-color: green;
}
</style>
<div contenteditable><canvas></canvas></div>
For some reason I'm not able to write anything into the contenteditable div and even the caret somehow disappear. What I'm doing wrong? A help would be appreciated.
CodePudding user response:
With a little Javascript you can sort of cheat it by adding a blank space and then forcing the caret to be placed at the end of the content
document.querySelector('.editor').onclick=e=>{
if( e.target==e.currentTarget ){
const setcaret=(n)=>{
let oSel=window.getSelection();
oSel.selectAllChildren( n );
oSel.collapseToEnd();
}
e.target.innerHTML = ' ';
setcaret( e.target );
}
};
.editor {
width: 100%;
min-height: 100%;
height: 100%;
background-color: black;
color: #fff;
padding:1rem;
}
canvas {
background-color: green;
width:100px;height:100px;margin:1rem;
}
<div contenteditable>
<canvas></canvas>
</div>
CodePudding user response:
.editor {
width: 100%;
min-height: 100%;
height: 100%;
background-color: black;
color: #fff;
position:relative;
}
canvas {
background-color: green; color: #fff;
}
<div contenteditable>
<canvas></canvas>
<p>Hi</p>
</div>
contenteditable
is saying that the div's content is editable, not the div itself, so use a p in the div to be your textbox or put a placeholder in, otherwise the content that you will be editing is the canvas. As other answers point out this is a Chrome bug, if you want to simulate the behaviour as other browsers, you can add a space in the div like this, otherwise the p solution still works.