美化input文件上傳

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload a file</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
    <link rel="icon" href="{% static 'images/favicon.png' %}">
</head>
<body class="container">
<form enctype="multipart/form-data" action="{% url 'upload' %}" method="post" class="my-md-5 mt-5  col-4"
      style="display: none">
    {% csrf_token %}
    <input type="file" name="file" class="form-control form-inline btn-outline-primary btn" id="upload_file">
    <input type="submit" id="submit">
</form>
<div>
    <div class="form-inline">
        <button id="file" class="btn btn-outline-primary mt-2 ml-5">選擇文件</button>
        <div class="form-text ml-3" id="info"></div>
    </div>
    <button id="upload" class="btn btn-outline-primary mt-2 ml-5">上傳</button>
</div>
<div class="alert"></div>

</body>
<script>
    document.getElementById("upload_file").onchange = function () {
        let filename = document.getElementById("upload_file").value;
        if (filename) {
            let temp = '';
            if (filename.includes("\\"))
                temp = filename.split('\\');
            else {
                temp = filename.split("/");
            }
            document.getElementById("info").innerHTML = temp[temp.length - 1]
        } else {
            document.getElementsByClassName("text-info")[0].innerHTML = "";
        }
    };

    document.getElementById("file").onclick = function () {
        document.getElementById("upload_file").click();
    };

    document.getElementById("upload").onclick = function () {
        if (document.getElementById("upload_file").value) {  // 如果其中有文件
            document.getElementById("submit").click();
        } else {
            let al = document.getElementsByClassName("alert")[0];
            let html = "";
            html += "<div class='alert alert-warning'>請選擇需要上傳的文件</div>";
            al.innerHTML = html;
        }
    }
</script>
</html>

主要思想:
form表單隱藏,用其他的控件來間接的控制其中的input

效果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章