自定义文件上传控件样式-input透明法

    xiaoxiao2021-07-20  118

    自定义文件上传控件样式-input透明法。

    作为一个刚入坑不久的程序小白,今天和一个自定义<input type="file">控件的工作斗智斗勇了一上午。通过各种膜拜大神们的资料,总算最后有了一个还算看的过去的解决方案,来记录一下。

    页面中,<input type="file">控件的默认显示

    在Chrome中是这样:在IE里是这样:

    要如何使它变成下面这样,点击此区域也能上传文件呢?

    原理:将input放进一个具有背景的div标签中,并且使input透明。

    html代码:

    <div class="inputbg"><input type="file"></div>

    css代码:

    .inputbg{ background: url(bg.jpg) no-repeat; position: relative; width: 311px; height: 162px; } .inputbg input{ position: absolute; top: 0; left: 0; opacity:0; filter:alpha(opacity=0); width: 311px; height: 162px; cursor: pointer; } </style>

    这个时候浏览器里显示是这样的。

    看起来正常,但是功能上确有问题。

    chrome:能够实现点击弹出文件窗口,但是在某些地方鼠标悬停的时候是 小手状,某些地方却是箭头。

    IE:虽然整个区域显示都是小手状,但是点击会出现竖线光标。而且IE10-IE6里都只有一小部分区域点击的时候会出现文件窗口,其他地方点击没有反应。

    问题1:去掉IE浏览器里的竖线光标。

    在html代码里给input添加属性unselectable="on"。此时,html代码变为:

    <div class="inputbg"><input type="file" unselectable="on"></div>

    问题2:解决Chrome浏览器里部分区域鼠标悬停是箭头的问题。

    添加font-size: 0;此时css代码变为:

    .inputbg{ background: url(bg.jpg) no-repeat; position: relative; width: 311px; height: 162px; } .inputbg input{ position: absolute; top: 0; left: 0; opacity:0; filter:alpha(opacity=0); width: 311px; height: 162px; cursor: pointer; font-size: 0; } </style>

    问题3:解决IE10-IE6里只有一小部分区域点击的时候会出现文件窗口,其他地方点击没有反应的问题。

    这个时候会发现,如果将font-size的值设置的足够大,就能解决这个问题。但是会影响Chrome里的功能。所以可以针对IE10-IE6专门设置。在css添加属性font-size: 150px\9;。现在css代码变为

    .inputbg{ background: url(bg.jpg) no-repeat; position: relative; width: 311px; height: 162px; } .inputbg input{ position: absolute; top: 0; left: 0; opacity:0; filter:alpha(opacity=0); width: 311px; height: 162px; cursor: pointer; font-size: 0; font-size: 150px\9; } </style>

    到现在为止所有浏览器都显示正常了。附上完整代码:

    html代码:

    <div class="inputbg"><input type="file" unselectable="on"></div>

    css代码:

    .inputbg{ background: url(bg.jpg) no-repeat; position: relative; width: 311px; height: 162px; } .inputbg input{ position: absolute; top: 0; left: 0; opacity:0; filter:alpha(opacity=0); width: 311px; height: 162px; cursor: pointer; font-size: 0; font-size: 150px\9; } </style>

    PS:之前看很多网上的其他资料发现,有的大神在定位的时候,用的是right: 0;还没理解是什么意思~所以还请大家多多指教~

    相关资源:WebUploader照片上传,file文件图片上传样式美化,多上传按钮处理,支持IE9

    最新回复(0)