從理論上看,實現(xiàn)起來比較容易,但實際工作的時候還是遇到兩個難點,這些難點歸結(jié)起來都是一個原因造成的,那就是瀏覽器的兼容性。在腳本中要用到兩個函數(shù):insertAdjacentHTML和removeChild,而恰好這兩個函數(shù)在Firefox下都不能正常使用。幾乎花費了一天的時候,在網(wǎng)上搜索著解決的方法,還好被找到了,也讓我大松一口氣。
具體兩個函數(shù)是這樣的:
<script type="text/javascript"> //刪除文件選擇框 function removeFile(id) { var new_tr = id.parentNode; try { //new_tr.removeNode(true); // just ie , not w3c; // other idea var tmp = new_tr.parentNode; // 為了在ie和firefox下都能正常使用,就要用另一個方法代替,最取上一層的父結(jié)點,然后remove. tmp.removeChild(new_tr); } catch(e) {} } //添加文件選擇框 function addFile(id) { var str = '<div><input type="file" runat="server" name="file" onKeyDown="this.blur();" oncontextmenu="return false" /><input type="button" value="刪除" style="height:22px;" onclick="removeFile(this)" /></div>' insertHtml("beforeend",document.getElementById(id),str); } </script>
頁面上這樣引用:
<div> <input type="button" value="添加附件(Add)" onclick="addFile('myfile')"> </div> <div id="myfile"> </div>
在addFile函數(shù)中引用了另一個函數(shù):insertHtml,這個函數(shù)主要是針對insertAdjacentHTML在firefox下無效的情況重寫的,具體可以通過搜索insertAdjacentHTML找到。
PS:清除file框的內(nèi)容
<input type=file name=ttt> <input type=button onclick="ttt.select();document.execCommand('Delete');" value=清除file框的內(nèi)容>
第二個案例
文件上傳,刪除效果圖:
剛開始:
點擊按鈕“選擇更多后”,可以添加很多選擇文件:
點擊按鈕“刪除”后:
實現(xiàn)代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>選擇文件</title> <style type="text/css"> *{ margin:0px; padding:0px; } div{ margin:10px; } </style> <script> //當(dāng)點擊添加更多時,增加一個DIV //先增加兩個input function addFile(){ var fragment=document.createDocumentFragment(); var divNode=document.getElementById("container"); var newDiv=document.createElement("div"); newDiv.setAttribute("id","file"); fragment.appendChild(newDiv); var newInput=document.createElement("input"); newInput.setAttribute("type","file"); newInput.setAttribute("name","選擇文件"); newDiv.appendChild(newInput); var newInput=document.createElement("input"); newInput.setAttribute("type","button"); newInput.setAttribute("value","刪除"); newInput.setAttribute("onclick","delFile()"); newInput.setAttribute("id","1"); newDiv.appendChild(newInput); divNode.appendChild(fragment); } function delFile(){ var divNode=document.getElementById("container"); divNode.removeChild(divNode.firstElementChild); } </script> </head> <body> <input type="button" value="選擇更多" onclick="addFile()"/> <div id="container"> <div id="file"> <input type="file" name="選擇文件"/> <input type="button" value="刪除" onclick="delFile()" /> </div> </div> </body> </html>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com