編輯器加載中...每次寫完的東西就忘了,下次用時還要重查資料重新寫,這是今天寫的一段測試代碼,保留下來,記錄給自已,同時分享給大家。 目標: 把下邊的這個上傳文件的input樣式和文字改成一句話“上傳圖片”,同樣實現上傳圖片的功能。 難點 1、不同瀏覽器的樣式表現不同。 2、文字如果只用click這樣的方式是不可以的。 3、input 上的文字是沒有辦法更改的。 解決的方法 用Javascript 嘗試了很多種方法,都不行,很麻煩。最后在網上看到一個人寫的一個辦法,給了些啟發,於是只用兩行CSS來解決這個問題。 如果直接在文字上加onclick事件來實現input的click(),這時選中文件是可以的,但這樣的方式在表單submit時就失效了。所以說,file input 必須是真正的點擊才有效果。 於是,就想了個辦法,把input 放在文字的上邊,弄成透明的,這樣在點文字時,實際是點擊了input,這樣就實現了文件的上傳。 第一步 我把input 用CSS改成比較大的,放在文字的后邊,這樣點文字時,其實是點了Input。
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>input type file test - zishu.cn</title> </head> <style> #uploadImg{ font-size:12px; border:1px solid #CC0000; position:absolute} #file{ position:absolute; z-index:100; margin-left:-180px; font-size:60px;opacity:10;filter:alpha(opacity=10); margin-top:-5px;} </style> <body> <span id="uploadImg"> <input type="file" id="file" size="1" > <a href="#">上傳圖片</a> </span> </body> </html>
第二步
再更改一下CSS,把多出的Input部分隱藏就可以了。
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>input type file test - zishu.cn</title> </head> <style> #uploadImg{ font-size:12px; border:1px solid #CC0000; overflow:hidden; position:absolute} #file{ position:absolute; z-index:100; margin-left:-180px; font-size:60px;opacity:10;filter:alpha(opacity=10); margin-top:-5px;} </style> <body> <span id="uploadImg"> <input type="file" id="file" size="1" > <a href="#">上傳圖片</a> </span> </body> </html>
最終的效果
再把Input弄成百分百透明就可以了
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>input type file test - zishu.cn</title> </head> <style> #uploadImg{ font-size:12px; overflow:hidden; position:absolute} #file{ position:absolute; z-index:100; margin-left:-180px; font-size:60px;opacity:0;filter:alpha(opacity=0); margin-top:-5px;} </style> <body> <span id="uploadImg"> <input type="file" id="file" size="1" > <a href="#">上傳圖片</a> </span> </body> </html>
就是這樣,知道了原理,你就可以隨意的更改文字和樣式了,改成圖片,改成按鈕都沒有問題。 2、這種方法看上去有點土,但簡單,實用,適用我電腦上的所有瀏覽器(ie6/ie7/firefox)。 File input 的樣式和文字的更改方法__適用於Firefox、IE等瀏覽器 原文地址為:http://www.zishu.cn/09/859.html