本文介绍了在contenteditable div中插入图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在loremipsum之间的div内插入图像:

Trying to insert an image inside a div, between lorem and ipsum:

$('#inpfile').on('change', function(){
	var img = $(this).prop('files')[0];
	document.execCommand('insertImage', img);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='file' id='inpfile' accept="image/jpeg, image/png, image/gif">
<br><br>
<div contenteditable>
lorem ipsum
</div>

什么都没发生.有帮助吗?

Nothing happens. Any help?

推荐答案

insertImage需要图像URL,并且您正在传递文件对象.您的代码实际上插入了<img>标记,但没有src属性,这就是为什么您看不到它的原因.

insertImage requires an image URL and you are passing a file object. Your code actually inserts an <img> tag but without src attribute, which is why you don't see it.

您可以使用FileReader检索图像URL.这是您要实现的工作代码:

You can retrieve image URL with a FileReader. Here is a working code for what you want to achieve:

$('#inpfile').on('change', function(){
    var file = $(this).prop('files')[0];
    var reader  = new FileReader();

    reader.addEventListener("load", function () {
        document.execCommand('insertImage', false, reader.result);
    }, false);

    if (file)
        reader.readAsDataURL(file);
});

这篇关于在contenteditable div中插入图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 10:55