js實(shí)現(xiàn)上傳按鈕并顯示縮略圖小輪子
前言
造這個(gè)小輪子的起因是因?yàn)槟J(rèn)提供的上傳文件的按鈕屬實(shí)丑陋了點(diǎn),而且還不能直接修改這個(gè)按鈕的樣式,所以就打算直接搞個(gè)小輪子方便日后需要時(shí)使用。使用原生js實(shí)現(xiàn)。那么直接上效果圖。
實(shí)現(xiàn)功能:
- 顯示上傳圖片縮略圖
- 實(shí)現(xiàn)上傳圖片格式限制
預(yù)覽效果圖如下
代碼實(shí)現(xiàn)
html代碼
<html> <head> <meta charset="utf-8" /> <title>uploalFileButton</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="file-container"> <div class="file-box"> <input type="file" class="file-btn" accept="image/png,image/jpeg,image/gif" id="file" /> <text>選擇文件</text> </div> <span id="showFileName"></span> <span id="fileerrorTip"></span> <div class="show_image"> <img src="" id="file_img" /> </div> </div> <script type="text/javascript" src="script.js"></script> </body> </html>
JavaScript代碼
(function(){ var fileBtn = document.getElementById('file'); var showName = document.getElementById('showFileName'); var errorTip = document.getElementById('fileerrorTip'); var fileImg = document.getElementById('file_img'); fileBtn.onchange = function(){ try{ var fileName = this.files[0].name; // 限制圖片上傳類型 if(fileName.indexOf("jpg") != -1 || fileName.indexOf("png") != -1) { errorTip.innerHTML = ""; showName.innerHTML = fileName; //顯示預(yù)覽圖片 var file = this.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onloadend = function(e) { fileImg.src = e.target.result; fileImg.style["display"] = "unset"; }; } else { showName.innerHTML = ""; errorTip.innerHTML = "您未上傳文件,或者您上傳文件類型有誤!"; return false } }catch(e){} } })()
CSS代碼
.file-container{ display: inline-block; } .file-box{ display: inline-block; position: relative; padding:8px 25px; overflow: hidden; color:#fff; background-color: #4387CD; border-radius: 5px; cursor: pointer; vertical-align: bottom; } .file-btn{ position: absolute; width: 100%; height: 100%; top: 0; left: 0; outline: none; filter:alpha(opacity=0); opacity: 0; } #showFileName, #fileerrorTip{ vertical-align: bottom; } .show_image{ width: 100px; padding: 5px; margin: 5px 0; border: 1px solid #ccc; border-radius: 5px; } .show_image img{ display: none; width: 100px; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS加密插件CryptoJS實(shí)現(xiàn)的Base64加密示例
這篇文章主要介紹了JS加密插件CryptoJS實(shí)現(xiàn)的Base64加密,結(jié)合實(shí)例形式分析了CryptoJS進(jìn)行base64加密的簡單實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-08-08uniapp使用uni-file-picker實(shí)現(xiàn)上傳功能
這篇文章主要介紹了uniapp使用uni-file-picker實(shí)現(xiàn)上傳功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-07-07js實(shí)現(xiàn)七夕表白彈幕效果 jQuery實(shí)現(xiàn)彈幕技術(shù)
這篇文章主要介紹了js實(shí)現(xiàn)七夕表白彈幕效果,jQuery實(shí)現(xiàn)彈幕技術(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08配置Grunt的Task時(shí)通配符支持和動(dòng)態(tài)生成文件名問題
這篇文章主要介紹了配置Grunt的Task時(shí)通配符支持和動(dòng)態(tài)生成文件名問題,需要的朋友可以參考下2015-09-09如何用JS實(shí)現(xiàn)網(wǎng)頁瀑布流布局
這篇文章主要介紹了如何用JS實(shí)現(xiàn)網(wǎng)頁瀑布流布局,幫助大家更好的利用JavaScript制作網(wǎng)頁,感興趣的朋友可以了解下2021-04-04