天天看點

自定義上傳元件樣式

寫在最前面

HTML自帶的上傳檔案元件樣式較醜陋。通常需要自定義元件樣式。思路是把上傳元件透明化(隐藏), 然後再自定義一個酷炫元件,點選酷炫元件的時候去模拟點選事件:模拟點選隐藏的元件

簡易demo
自定義上傳元件樣式
code
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style>

        .fileClassDiv {

            margin: px;
            padding: px;
            border: px solid #3089dc;
            text-align: center;
            font-size: px;
            width: px;
        }

        .fileClassInput {
            filter: alpha(opacity=);
            opacity: ;
            width: ;
            height: ;
        }
    </style>
</head>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>

    $(function () {
        // + 監聽
        $(document).on("click", ".fileClassDiv", function () {
            console.log(this);

            var fileInputElement = $(this).parent().children(".fileClassInput");
            fileInputElement.trigger("click");
        })
    });

    // 上傳視訊input監聽
    $(document).on("change", ".fileClassInput", function () {

        // 視訊名字
        var videoDivElement = $(this).parent().children(".fileClassDiv");

        // 視訊名字回填div

        videoTip = $(this).val().substring($(this).val().lastIndexOf("\\") + );

        videoDivElement.html(videoTip);
    });

</script>

<body id="bodyId">
    <div class="fileClassDiv">+</div>
    <input class="fileClassInput" type="file"/>
</body>
</html>