700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > input type=file选择图片按钮样式修改与图片预览

input type=file选择图片按钮样式修改与图片预览

时间:2018-05-12 15:09:52

相关推荐

input type=file选择图片按钮样式修改与图片预览

1 背景

通过上图我们可以看到input type=file按钮的默认样式,非常不美观,如果要自定义该按钮的样式,要如何实现呢?

2 方式1样式

input覆盖整个按钮区域,并且设置完全透明

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {position: relative;width: 100px;height: 100px;line-height: 100px;background-color: #ccc;text-align: center;}#file {width: 100%;height: 100%;position: absolute;left: 0;top: 0;opacity: 0;}</style></head><body><div>选取图片<input type="file" accept="image/*" id="file"></div></body></html>

3 方式2样式

input隐藏,通过label设置按钮样式

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>div {width: 100px;height: 100px;line-height: 100px;background-color: #ccc;text-align: center;}#file{display: none;}label {display: block;width: 100%;height: 100%;}</style></head><body><div><input type="file" accept="image/*" id="file"><!-- 将label与input建立关系,点击label等于点击了input --><label for="file">选取图片</label></div></body></html>

4 图片预览

<script src="/jquery/1.10.2/jquery.min.js"></script><script>$(function() {// input选取文件后会触发change事件$('#file').on('change', function(event) {console.log(event.target.files) //选取的文件对象数组// 通过FileReader读取文件对象信息var reader = new FileReader()reader.onload = function(e) {var img = new Image()img.src = e.target.result //读取结果会转为base64数据格式img.style.width = '200px'document.body.appendChild(img)}reader.readAsDataURL(event.target.files[0])})})</script>

5 js动态创建input方式

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.file {width: 100px;height: 100px;line-height: 100px;background-color: #ccc;text-align: center;}</style></head><body><div class="file">选取图片</div><script src="/jquery/1.10.2/jquery.min.js"></script><script>$(function() {$('.file').on('click', function() {// 动态创建input元素,type为file,样式为隐藏,并追加到body中var input = $('<input/>')input.prop('type', 'file')input.css('display', 'none')$('body').append(input)// 监听选取文件触发的change事件input.on('change', function(event) {console.log(event.target.files) //选取的文件对象数组// 通过FileReader读取文件对象var reader = new FileReader()reader.onload = function(e) {var img = new Image()img.src = e.target.result //读取结果会转为base64数据格式img.style.width = '200px'document.body.appendChild(img)}reader.readAsDataURL(event.target.files[0])// 完成选取文件后,从dom中自我删除input.remove()})// 自动触发click事件去选取文件input.click()})})</script></body></html>

6 效果展示

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。