input file类型自定义样式-按钮

    xiaoxiao2021-12-14  23

    我们在做页面时有时候为了让上传这种类型的输入看起来更加美观,但是由于其自身往往是无法定义样式的,所以我们经常用按钮来 “替代” 它,接下来讲讲其原理和实践过程。原理:为了让input[type='file']看起来更像一个button,我们首先先采用绝对定位定义一个<a>标签,然后采用绝对定位在相同的位置定义一个和<a>大小完全相同的<input type='file'>,并把其透明度设置为0,最后再定义一个div显示上传的文件名即可。为了方便吧css直接写在html里,简要代码如下:

    <!doctype html> <html> <head> <style> * { margin: 0; padding: 0; } /*蓝色按钮,绝对定位*/ .blueButton { position: absolute; display: block; width: 100px; height: 40px; background-color: #00b3ee; color: #fff; text-decoration: none; text-align: center; font:normal normal normal 16px/40px 'Microsoft YaHei'; cursor: pointer; border-radius: 4px; } .blueButton:hover { text-decoration: none; } /*自定义上传,位置大小都和a完全一样,而且完全透明*/ .myFileUpload { position: absolute; display: block; width: 100px; height: 40px; opacity: 0; } /*显示上传文件夹名的Div*/ .show { position: absolute; top:40px; width: 100%; height: 30px; font:normal normal normal 14px/30px 'Microsoft YaHei'; } </style> <script src="../jquery-3.1.0.min.js"></script> <title>file自定义上传</title> </head> <body> <a href='javascript:void(0);' class="blueButton">选择文件</a> <input type="file" class="myFileUpload" /> <div class="show"></div> </body> </html> <script> $(document).ready(function() { $(".myFileUpload").change(function() { var arrs=$(this).val().split('\\'); var filename=arrs[arrs.length-1]; $(".show").html(filename); }); }); </script> 点击后页面如下:

    转载请注明原文地址: https://ju.6miu.com/read-968549.html

    最新回复(0)