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>
    

    以上。

  • 相关阅读:
    .net5访问共享目录
    SqlServer 查询数据库表结构
    SqlServer查询所有表结构信息
    sqlserver 清掉工件号重复的数据
    产生18位的随机数作为bigint
    sql多表联合修改
    sp_addlinkedserver在存储过程中使用
    sqlserver 中随机取数据
    Winform选择目录路径与选择文件路径
    WinFrom 右下角弹出提示框
  • 原文地址:https://www.cnblogs.com/marvin-wen/p/14441486.html
Copyright © 2011-2022 走看看