zoukankan      html  css  js  c++  java
  • input file如何进行自定义的美化和预览

    前言

      本篇博客解决两个问题:一是原生的<input type="file"/>非常的丑陋,本篇将介绍最简单的美化方法;二是原生的<input type="file"/>不支持实时预览,本篇将介绍一种简单地实现预览的方法。

    美化

      思路:将原生的<input type="file"/>隐藏起来,用其他图片或者按钮来替代,当点击图片或者按钮时调用<input type="file"/>click方法。

    html代码如下:

    <img src="替代图片的路径" onclick="input_file()">
    <input type="file" name="file" id="input-file">
    

    js代码如下:

    <script>
        function input_file() {
            $('#input-file').click();
        }
    </script>
    

    预览

      思路:在上一步的基础上,我们可以在<input type="file"/>上添加onchange事件,当我们选择了要上传的图片时,通过修改src实现图片的预览。

    html代码如下:

    <img src="替代图片的路径" onclick="input_file()" id="img-preview">
    <input type="file" name="file" onchange="img_preview(this)" id="input-file">
    

    js代码如下:

    <script>
        function input_file() {
            $('#input-file').click();
        }
    
        function img_preview(obj) {
            var file = obj.files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {    //成功读取文件
                var img = document.getElementById("img-preview");
                img.src = e.target.result;   //或 img.src = this.result / e.target == this
            };
        }
    </script>
    

    以上。

  • 相关阅读:
    模板
    Codeforces Round #598 (Div. 3)
    Codeforces Round #589 (Div. 2)
    日记集
    模板
    Codeforces Round #592 (Div. 2)
    Linux挂载新盘
    VMware实用技巧
    useradd和adduser的区别
    ubuntu VSFTPD搭建FTP服务器 提示530错误
  • 原文地址:https://www.cnblogs.com/marvin-wen/p/14441486.html
Copyright © 2011-2022 走看看