javascript 如何将图像传递到 html textarea
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30279671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an image into a html textarea
提问by SvenSune
I'm wondering how to pass an image from an image-gallery into a html-textarea. Should i use jquery/javascript and do you know some good tutorial on this function?
我想知道如何将图像从图像库传递到 html-textarea。我应该使用 jquery/javascript 吗,你知道关于这个功能的一些好的教程吗?
回答by Blauharley
After choosing an image via os built-in selector
通过 os 内置选择器选择图像后
<input type="file"../>
you can pass image data(base64 encoded string) to an image tag located within a editable div by using file reader api.
您可以使用文件阅读器 api 将图像数据(base64 编码字符串)传递给位于可编辑 div 内的图像标签。
Full example:
完整示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<style>
#textarea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
</style>
<body>
<input class="file" type='file' id="imgSel" />
<div id="textarea" contenteditable>
<img contenteditable="false" style="width:45px" id="myimg" />
I look like a textarea
</div>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('myimg').setAttribute('src',e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
document.getElementById('imgSel').onchange = function () { //set up a common class
readURL(this);
};
</script>
</body>
</html>
How to make and editable div look like a textarea element:
如何使可编辑的 div 看起来像一个 textarea 元素:
#textarea {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 118px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
<div id="textarea" contenteditable>
<img contenteditable="false" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Koala-ag1.jpg" width="120" height="100"/>
I look like a textarea</div>
you can set contenteditable="false"on img element to make it not editable.
您可以在 img 元素上设置contenteditable="false"以使其不可编辑。