I need to manipulate img
element before inserting it into a contenteditable
div.
here next is my attempt. to do ..
- add
EditorImgs
class to the image assign - add
src
to that image
window.addEventListener('load', function () { var ImgCmd = document.getElementById('ImgCmd'); var uploader = document.getElementById('ImageUploader'); ImgCmd.addEventListener('click', () => uploader.click()); }); var editer = document.getElementById('design_view'); function uploadFile(e) { let file = e.target.files[0]; editer.focus(); let url = URL.createObjectURL(file); // console.log(url); // blob:https://localhost:34564/1v9m120z-y982-4np3-a8ah-9uead3dj6743 var Img = document.createElement('img'); Img.src = url; Img.setAttribute("class", "EditorImgs"); document.execCommand('insertImage', false, Img); }
.EditorImgs { border: 1px solid #d3d3d3; overflow: hidden; resize: both; width: 200px; height: 150px; }
<input id="ImageUploader" type="file" hidden="hidden" onchange="uploadFile(event)" /> <button id="ImgCmd">Insert Image</button> <div contenteditable id="design_view"></div>
Advertisement
Answer
When using document.execCommand('insertImage')
, the third argument should be the URL, not an image element.
document.execCommand('insertImage', false, url);
If you want to style the image, you could use document.execCommand('insertHTML')
or Range#insertNode
.
var range = window.getSelection().getRangeAt(0); range.insertNode(Img);
window.addEventListener('load', function () { var ImgCmd = document.getElementById('ImgCmd'); var uploader = document.getElementById('ImageUploader'); ImgCmd.addEventListener('click', () => uploader.click()); }); var editer = document.getElementById('design_view'); function uploadFile(e) { let file = e.target.files[0]; editer.focus(); let url = URL.createObjectURL(file); var Img = document.createElement('img'); Img.src = url; Img.setAttribute("class", "EditorImgs"); var range = window.getSelection().getRangeAt(0); range.insertNode(Img); }
.EditorImgs { border: 1px solid #d3d3d3; overflow: hidden; resize: both; width: 200px; height: 150px; }
<input id="ImageUploader" type="file" hidden="hidden" onchange="uploadFile(event)" /> <button id="ImgCmd">Insert Image</button> <div contenteditable id="design_view"></div>