我正在使用iframe构建我自己的WYSIWYG编辑器,我想找到一种简单插入图像的方法!我已经使用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');
}
这非常有效,但我正在努力使用“插入图像按钮”因为我对编码很新,所以我试着这样做:
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>
你可以在这里查看关于这个图像上传问题的完整文章: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)}