效果预览
完整代码范例
<! DOCTYPE html >
< html lang = " en" >
< head>
< meta charset = " UTF-8" />
< meta http-equiv = " X-UA-Compatible" content = " IE=edge" />
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" />
< title> 纯前端选择并预览图片</ title>
</ head>
< body>
< button onclick = " chooseImg ( ) " > 选择图片</ button>
< div style = " padding-top : 10px; " >
< img id = " imgBox" width = " 100" > </ img>
</ div>
< script>
function chooseImg ( ) {
let input = document. createElement ( "input" ) ;
input. setAttribute ( "type" , "file" ) ;
input. setAttribute ( "multiple" , "multiple" ) ;
input. accept = "image/*" ;
input. addEventListener ( "change" , ( e ) => {
let file = e. path[ 0 ] . files[ 0 ] ;
const windowURL = window. URL || window. webkitURL;
let filePath = windowURL. createObjectURL ( file) ;
document. getElementById ( "imgBox" ) . setAttribute ( 'src' , filePath)
} ) ;
input. click ( ) ;
}
</ script>
</ body>
</ html>
核心技术解析
通过创建文件输入框节点,触发打开资源管理器 通过 createObjectURL 函数将选择的图片对象转换为 URL ,方便前端渲染显示图片