• 【前端】【探究】HTML - input类型为file时如何实现自定义文本以更好的美化


    想到英语四级考了两次都没过,我觉得要多使用英文,所以本文使用英文书写。

    本文讲述了遇到的问题,解决的思路,并讲述了解决方案,也许对你会有帮助。

    2022年9月25日凌晨3点20分@萌狼蓝天

    Problem description

    when we want to use input of file type, it has a very serious problem : the text content(文本内容) displayed (显示)cannot be set by us , And the default text display varies(不同) from browser to browser!

    • It displays on Edge as shown below

    image

    • It displays on Webstorm default preview browser(Webstorm默认预览浏览器) as shown below

    image

    Solution

    We can use a button to select file and use a text box to show selected file's name , instead of file type input.

    This does not mean that we discard input of file type , just hide it and use other elements to control it , it's still the one that actually works.(这并不意味着我们抛弃了文件类型的 "input",只是隐藏了它并使用其他元素来控制它,它仍然是真正起作用的)

    Example

    1.Use Button to select file

    Use display:none to hiden file type input

    1. <input id="selectFile" type="button" value="选择文件" onclick="document.getElementById('fileUp').click()">
    2. <input type="file" style="display: none" name="fileUp" id="fileUp">

    When we click on the button with the id selectFile, Javascript will get the element of file type input, and then execute its click event(点击事件).

    2.Use a box to show selected file‘s name

    You can use a text type inputp tags、 div tags and so on.

    Now,I'll use a text type input as case to write a demo

    Prefor a text type input and set it read only, the code is as follows:

    <input type="text" readonly id="fileSelected" value="未选择任何文件" >

    Now, we have to thinking about how to get the selected file'name.

    Obviously, we need to read the name of the uploaded file from the input of the file type, the code is as follows:

    <input type="text" readonly id="fileSelected" value="未选择任何文件" onclick="document.getElementById('fileUp').click()" style="border: none;">

    tips : you can use outline:none to make the element outline hiden.

    The complete code

    1. <input id="selectFile" type="button" value="选择文件" onclick="document.getElementById('fileUp').click()">
    2. <label for="selectFile">
    3. <input type="text" readonly id="fileSelected" value="未选择任何文件" onclick="document.getElementById('fileUp').click()" style="border: none;">
    4. label>
    5. <input type="file" style="display: none" name="fileUp" id="fileUp"
    6. onchange="document.getElementById('fileSelected').value=this.value">

    image

  • 相关阅读:
    【Leetcode】207.课程表
    2022年后端工程师提升开发效率神器推荐
    解决git@github.com: Permission denied (publickey)
    istio 初识
    Chrome浏览器删除网站cookies的解决方案
    letax环境过程记录 20220831
    【mysql篇-进阶篇】SQL优化
    【傅里叶梅林图像配准】用于图像配准的傅里叶梅林相位相关性的实现(Matlab代码实现)
    组原必备知识点
    基于DPU和HADOS-RACE加速Spark 3.x
  • 原文地址:https://blog.csdn.net/ks2686/article/details/127034634