自定義input上傳圖片框


            <div id="input_img_father_div">
                <!--設置input的position為absolute,使其不按文檔流排版,並設置其包裹整個布局 -->
                <!-- 設置opactity為0,使input變透明 -->
                <!-- 只接受jpg,gif和png格式 -->
                <input id="upload_input" type="file" accept="image/*"/>
                <!-- 自定義按鈕效果 -->
                <div id="input_img_btn_div">
                    <span id="input_img_btn_span">上傳圖片:</span>
                    <img id="upload" src="./upload.png" style="width: 40px; height: 40px; vertical-align: middle;"/>
                </div>
            </div>
        </div>

css文件:

#input_img_father_div {
    position: relative;
    width: 170px;
    height: 200px;
    vertical-align: middle;
    opacity: 60;
    background-color: #c6c6c6;
    display: flex; /*flex彈性布局*/
    justify-content: center;
    align-items: center;
}

#upload_input {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    opacity: 0;
    width: 170px; 
    height: 200px;
}

#input_img_btn_div {
    text-align: center;
    display: flex;
    flex-direction: column; /*元素的排列方向為垂直*/
    justify-content: center; /*水平居中對齊*/
    align-items: center; /*垂直居中對齊*/
}

#input_img_btn_span {
    font-size: 24px;
    vertical-align: middle;
}
img#upload {
width: 170px;
height: 200px;
}

實現圖片預覽:

    {# 圖片預覽 #}
    <script>
        {# 上傳樣板圖片預覽 #}
        $("#upload_input").change(function () {
            var objUrl = getObjectURL(this.files[0]);//獲取文件信息
            console.log(objUrl)
            if (objUrl) {
                $('span#input_img_btn_span').hide();
                $('img#upload').show();
                $("img#upload").attr("src", objUrl);
            }
        });
        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        }
    </script>

 最終效果:

上傳前:                      上傳后:

                          


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM