input[type=file]樣式更改以及圖片上傳預覽


  以前知道input[type=file]可以上傳文件,但是沒用過,今天初次用,總感覺默認樣式怪怪的,想修改一下,於是折騰了半天,總算是小有收獲。

  

  以上是默認樣式,這里我想小小的修改下:

  HTML代碼如下:

<form action="" name="file" class="file">
    上傳文件<input type="file" id="img" name="img">
</form>

  

  css代碼如下:

<style>
    .file{
	width: 75px;
        height: 25px;
	line-height: 25px;
	text-align: center;
	background-color: green;
	position:relative;
    }
    .file input{
	width: 75px;
        height: 25px;
	opacity:0;
	filter:alpha(opacity=0);
	position:absolute;
	left:0;
	top:0;
    }
</style>        

  

  更改后,效果如下(樣式很丑,這里主要是闡述下怎么更改input[type=file]默認樣式的)

  

 

  下面來說下使用input[type=file]上傳圖片實現預覽效果的。

  

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.file{
		   width: 75px;
		    height: 25px;
		    line-height: 25px;
		    text-align: center;
		   background-color: green;
		   position:relative;
		}
		.file input{
		   width: 75px;
		    height: 25px;
		   opacity:0;
		   filter:alpha(opacity=0);
		   position:absolute;
		   left:0;
		   top:0;
		}
	</style>
</head>
<body>
	<form action="" name="file" class="file">
		上傳文件
		<input type="file" id="img" name="img">
	</form>
	<div id="dd"></div>
	<script>
		var file = document.getElementById("img");
		file.onchange = function(){  // 文本框內容改變時觸發
			var files = this.files; // 獲取文件的數量
			for(var i=0;i<files.length;i++){
				readers(files[i])
			}
		}
		function readers(fil){
			var reader = new FileReader();  // 異步讀取存儲在用戶計算機上的文件
			reader.readAsDataURL(fil); // 開始讀取指定的Blob對象或File對象中的內容
			reader.onload = function(){
				document.getElementById("dd").innerHTML += "<img src='"+reader.result+"'>";  // 添加圖片到指定容器中
			}; 
		}
	</script>
</body>
</html>

  

 


免責聲明!

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



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