上传图片动态预览(兼容主流浏览器)

来源:互联网 发布:快速copy软件 编辑:程序博客网 时间:2024/05/20 18:43

允许转载,但请注明出处:http://blog.csdn.net/sysuzjz/article/details/41800605

做这个功能初始目的是为了在提交编辑前先查看效果,当然仅限于图片。

核心代码来源于网上,经测验有效

假设HTML如下:

<body>    <img src="#" id="logo" alt="上传的图片">    <input type="file" accept="image/*" id="upload" /></body>

JS如下:

document.getElementById("upload").onchange = function(){    var objUrl = getObjectURL(this.files[0]) ;    if (objUrl) {        document.getElementById("logo").setAttribute("src", objUrl) ;    }};//建立一個可存取到該file的urlfunction getObjectURL(file) {    var url = null ;     if (window.createObjectURL!=undefined) { // basic        url = window.createObjectURL(file) ;    } else if (window.URL!=undefined) { // mozilla(firefox)        url = window.URL.createObjectURL(file) ;    } else if (window.webkitURL!=undefined) { // webkit or chrome        url = window.webkitURL.createObjectURL(file) ;    }    return url ; }


0 0
原创粉丝点击