美文网首页
怎么简便地去掉html中难看的文件上传按钮并实现图片预览功能?(

怎么简便地去掉html中难看的文件上传按钮并实现图片预览功能?(

作者: 王远清orz | 来源:发表于2019-05-14 11:59 被阅读0次

    问题描述

    通常的文件上传按钮是这样的:


    image

    选择了文件过后是这样的:


    image
    很显然,这样的按钮并不好看。

    解决方法

    用一个label标签来装载样式,其for属性指向type=file的input,然后将input标签隐藏(display="none"),这样,在点击label时就会触发input弹出文件选择框。

    实例演示

    代码:

    
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    
    <body>
    <label for="file"><img src="images/2.jpg"></label>
    <input type="file" id="file" name="" style="display: none"/>
    <div id="image" style="width:100px;height:100px; background:#CCCCCC; ">
        <img src="images/2.jpg" height="100px" width="100px" border="5px"/>
    </div>
    </body>
    <script>
        document.getElementById('file').onchange = function() {
            var imgFile = this.files[0];
            var fr = new FileReader();
            fr.onload = function() {
                document.getElementById('image').getElementsByTagName('img')[0].src = fr.result;
            };
            fr.readAsDataURL(imgFile);
        };
    </script>
    
    </html>
    

    效果:


    image
    image

    原文地址:https://blog.csdn.net/zhoucheng05_13/article/details/53839552

    相关文章

      网友评论

          本文标题:怎么简便地去掉html中难看的文件上传按钮并实现图片预览功能?(

          本文链接:https://www.haomeiwen.com/subject/pnfsaqtx.html