如何使用我自己的所见即所得编辑器插入图像

How to insert images with my own WYSIWYG editor

本文关键字:编辑器 插入 图像 所见即所得 自己的 何使用 我自己      更新时间:2024-03-10

我正在使用iframe构建我自己的所见即所得编辑器,我想找到一种简单插入图像的方法我已经得到了粗体、斜体、H1和H2,使用JS:

    function bold(){
    editor.document.execCommand("bold", false, null)
    }
    function italic(){
    editor.document.execCommand("italic", false, null)
    }
    function h1(){
    editor.document.execCommand('formatBlock',false,'h1');
    }
    function h2(){
    editor.document.execCommand('formatBlock',false,'h2');
    }

这很有效,但我很难使用"插入图像按钮"由于我对编码真的很陌生,我尝试了这个:

function image(){
var image = prompt ("Paste or type a link", "http://")
editor.document.execCommand("createImage", false, image)

但这行不通。我的意图是让用户有可能从他们的电脑和/或互联网上传图像。请,如果有人知道如何插入图像。。。帮助

非常感谢

您是否尝试使用相对链接格式化图像位置,其中@符号位于图像位置之前。你的代码和解释也没有解释他们是从我的文档这样的位置的机器上传图像,还是严格从http链接上传图像。

要使用Javascript和HTML从本地机器上传,您可以签出此代码。您的问题是在编写自定义Javascript函数时经常出现的问题。

<script type='text/javascript'>
function main()
{
var inputFileToLoad = document.createElement("input");
inputFileToLoad.type = "file";
inputFileToLoad.id = "inputFileToLoad";
document.body.appendChild(inputFileToLoad);
var buttonLoadFile = document.createElement("button");
buttonLoadFile.onclick = loadImageFileAsURL;
buttonLoadFile.textContent = "Load Selected File";
document.body.appendChild(buttonLoadFile);
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
    var fileToLoad = filesSelected[0];
    if (fileToLoad.type.match("image.*"))
    {
        var fileReader = new FileReader();
        fileReader.onload = function(fileLoadedEvent) 
        {
            var imageLoaded = document.createElement("img");
            imageLoaded.src = fileLoadedEvent.target.result;
            document.body.appendChild(imageLoaded);
        };
        fileReader.readAsDataURL(fileToLoad);
    }
}
}
main();
</script>

您可以在这里查看关于使用Javascript和HTML5上传图像的完整文章:https://thiscouldbebetter.wordpress.com/2012/12/20/uploading-and-displaying-an-image-from-a-file-using-html5-and-javascript/

它应该是"insertimage"而不是createImage。

function image(){var image = prompt ("Paste or type a link", "http://")editor.document.execCommand("insertimage", false, image)}

您可以使用此后

    var insertImgTag = document.createElement("div");
    insertImgTag.id = "insertImgTag";
    if (document.getSelection().anchorNode != null) {
    document.getSelection().getRangeAt(0).insertNode(insertImgTag);}
    $("#insertImgTag")
            .parent()
            .html(
                "<img src=/images/" + $("#name").val() + " width='" + imgWidth + "%' alt='" + imgAlt + "'>"
            );

根据这篇文章

,我在自己的javascript编辑器中使用了它