您的位置:首页 > Web前端 > CSS

input[type=file]样式更改以及图片上传预览

2017-12-18 22:22 501 查看
  以前知道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
对象或[code]File
对象中的内容
reader.onload = function(){
document.getElementById("dd").innerHTML += "<img src='"+reader.result+"'>"; // 添加图片到指定容器中
};
}
</script>
</body>
</html>
[/code]

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: