[英]insert image in a iframe at caret location
對於富文本框。 我想在插入符號的位置插入用戶選擇的圖片。
首先我試過:
var loadImage = function(event) {
var editor = editFrame.document;
editor.execCommand("insertImage", false, event.target.files[0] );
};
我只得到一個斷開的鏈接圖標,但位於 iframe 中的當前位置。 沒有圖像。 然后我被告知要嘗試:
var loadImage = function(event) {
var editor = document.getElementById('editFrame');
editor.src = URL.createObjectURL(event.target.files[0]);
};
這不是我想要做的,但在這種情況下,我沒有斷開的鏈接問題並且圖像正常加載。
我怎樣才能獲得兩個世界中最好的? :)
有人可以解釋我如何在預期的地方加載圖像嗎? 在插入符號位置? 我讀了一些東西,但作為一個初學者,這一切都讓我很困惑。
請只使用 javascript,好嗎? 我的意思是@David Bray 提供的解決方案工作正常。 但它使用 JQuery,我不知道它在做什么......或者有人可以將 JQuery 翻譯成 Javascript?
取 10 並使用如何在使用 execCommand 插入后獲取圖像元素?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
</form>
<div contenteditable id="doc">type here .. put you cursor here [.] and put an inmage in the queue</div>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#doc').focus();
document.execCommand("insertHTML", false, "<img src='" + e.target.result + "' />");
console.log( 'done');
}
reader.readAsDataURL( input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
});
</script>
</body>
</html>
這是 David Bray 腳本的純 JavaScript 版本,並進行了各種其他更改。 它與他的答案非常接近,可以將其視為不同的版本,但太不同而無法僅編輯原始答案。 突出顯示的一個補充是我在加載圖像后將輸入元素值設置為空。 如果你不這樣做並且你刪除了一個圖像,它將不允許你重新加載它。
const imgInp = document.getElementById('imgInp');
imgInp.onchange = function() {
if (imgInp.files && imgInp.files[0]) {
const reader = new FileReader();
reader.onload = function(event) {
// Works without the below focus, but you may need it if you modify it.
document.getElementById('doc').focus();
document.execCommand('insertImage', false, event.target.result);
imgInp.value = "";
}
reader.readAsDataURL(imgInp.files[0]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.