首页 文章

如何使用我自己的WYSIWYG编辑器插入图像

提问于
浏览
1

我正在构建我自己的WYSIWYG编辑器,使用iframe, I'd like to find just a way to simply insert an image! 我已经使用JS获得了粗体样式,斜体样式,H1和H2:

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');
    }

这很好但是 I'm struggling with "Insert image button" 因为我是编码的新手,所以我试着这样做:

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

但这不起作用 . 我的意图是用户可以从他们的计算机和/或互联网上传图像 . 如果有人知道如何插入图片,请帮助!

A LOT OF THANKS IN ADVANCE!

1 回答

  • 2

    您是否尝试使用@符号位于图像位置之前的相对链接来格式化图像位置 . 您的代码和说明也无法解释他们是否将图像从他们的机器上传到像我的文档这样的位置,或者他们是否严格上传图像和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和HTML 5的图像上传问题的完整文章:https://thiscouldbebetter.wordpress.com/2012/12/20/uploading-and-displaying-an-image-from-a-file-using-html5-and-javascript/

相关问题