在线JQuery引用:
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
HTML源码:
<html>
<head>
<style>
#box{
width: 300px;
height: 300px;
border: 2px solid #858585;
}
#imgshow{
width: 100%;
height: 100%;
}
#pox{
width: 70px;
height: 24px;
overflow: hidden;
}
#imgshow2{ width:50px; height:50px}
</style>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<p id="box">
<img id="imgshow" src="" alt=""/>
</p>
<p id="pox">
<input id="filed" type="file" accept="image/*"/>
</p>
<div>
<input type="button" value="测试" onclick="javascript:button_onclick();" />
</div>
<p id="box2">
<img id="imgshow2" src="" alt="" />
</p>
<script>
//用来保存图片的全局变量,以便在别处使用该图片
var ori={}
//在input file内容改变的时候触发事件
$('#filed').change(function(){
//获取input file的files文件数组;
//$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
//这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
var file = $('#filed').get(0).files[0];
//创建用来读取此文件的对象
var reader = new FileReader();
//使用该对象读取file文件
reader.readAsDataURL(file);
//读取文件成功后执行的方法函数
reader.onload=function(e){
ori=e;
//读取成功后返回的一个参数e,整个的一个进度事件
console.log(e);
//选择所要显示图片的img,要赋值给img的src就是e中target下result里面的base64编码格式的地址
$('#imgshow').get(0).src = e.target.result;
}
}
)
function button_onclick(){
$('#imgshow2').get(0).src = ori.target.result;
}
</script>
</body>
</html>
实现效果: