已解决
利用JavaScript查看照片
来自网友在路上 189889提问 提问时间:2023-10-31 11:16:19阅读次数: 89
最佳答案 问答题库898位专家为你答疑解惑
刚入门学习js,主要是兴趣使然,想做一个打开任意的文件夹,显示里面的照片文件,由于js不能获取绝对路径,使用
FileReader进行显示照片,具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>读取文件显示图片</title>
</head>
<style>*{margin: 0px;padding: 0px;}img{width: 800px;height: 600px;max-width:100%;max-height:100%;}button{width: 100px;height: 30px;border-radius: 5px;background: green;color: #fff;margin:12%;margin-top: 1%;}
</style><body>
<br>
<br>
<br>
<br><br>
<input type="file" id="fileInput" onchange="selectFolder()" webkitdirectory directory multiple>
<div style="text-align:center"><span style="color:blue;font-size:20px;" id="sp"><b></b></span>
</div>
<br>
<div style="text-align:center"><img id="pic" src=""><br><button id='prev' onclick="prev()">上一张</button><button id='next' onclick="next()">下一张</button>
</div>
<div id="result"></div><script language="javascript">//读取图片类型function selectFolder() {var inputBox = document.getElementById("fileInput");var index = 0;var imgext = new Array("png","jpg","jpeg","bmp","gif");var files = inputBox.files;var ss = [];for (var i = 0; i < files.length; i++) {//判断是不是图片文件,不是的话不存入ssvar ind= files[i].name.split(".")[1];//判断是不是包含图片文件if (imgext.includes(ind)){console.log(files[i]);ss.push(files[i]);}}//将局部变量ss变为全局变量globalss = ss;globalindex = index;if (ss.length==0){alert('没有照片文件!')}else{document.getElementById("sp").innerHTML = 1+"/"+globalss.length;var reader = new FileReader();globalreader = reader;reader.readAsDataURL(ss[0]);//发起异步请求reader.onload = function(){pic.src = this.result;//读取完成后,数据保存在对象的result属性中this.result就是reader.readAsDataURL(ss[0])console.log(this.result)}}}function prev(){//判断index是不是大于0if (globalindex>0){globalindex = globalindex-1globalreader.readAsDataURL(globalss[globalindex]);document.getElementById("pic").src=this.result;document.getElementById("sp").innerHTML = globalindex+1+"/"+globalss.length;}else{alert('这是第一张图片!')}}function next(){globalindex = globalindex+1//alert(index);//判断index是不是大于ss的长度if (globalindex>=globalss.length){alert('已经是最后一张图片了!')}else{globalreader.readAsDataURL(globalss[globalindex]);document.getElementById("pic").src=this.result;document.getElementById("sp").innerHTML = globalindex+1+"/"+globalss.length;}}</script></body>
</html>
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"利用JavaScript查看照片":http://eshow365.cn/6-28578-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!