这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
本文为大家分享的是一款效果非常酷的文件上传表单域美化特效。有 7 种不同的美化文件上传域的效果,很时尚,感兴趣的小伙伴们可以参考一下
一款效果非常时尚的文件上传表单域美化特效,下面给出制作的简要教程。
先上几个效果饱饱眼福:
使用方法
这些文件上传域的美化使用的方法都是隐藏原生的元素,然后使用一个
html 结构
该文件上传域美化效果最基本的 HTML 结构如下:
- <input type="file" name="file" id="file" class="inputfile" />
- <label for="file">
- Choose a file
- </label>
CSS 样式
首先需要隐藏元素。这里不能使用 display: none 或 visibility: hidden 来隐藏它,因为这样做只后,元素里的值不会被上传到服务器端,而且按 TAB 键时这个元素也不会被找到。隐藏的方法如下:
- .inputfile {
- width: 0.1px;
- height: 0.1px;
- opacity: 0;
- overflow: hidden;
- position: absolute;
- z - index: -1;
- }
接下来给
- .inputfile + label {
- font - size: 1.25em;
- font - weight: 700;
- color: white;
- background - color: black;
- display: inline - block;
- }
- .inputfile: focus + label,
- .inputfile + label: hover {
- background - color: red;
- }
当鼠标滑过 label 时需要将光标显示为一个小手的形状。
- .inputfile + label {
- cursor: pointer;
- /* "hand" cursor */
- }
为了制作可以使用键盘导航的效果,需要添加下面的代码。
- .inputfile: focus + label {
- outline: 1px dotted#000;
- outline: -webkit - focus - ring - color auto 5px;
- }
-webkit-focus-ring-color auto 5px 可以在 Chrome,Opera 和 Safari 浏览器中获取默认的边框外观。
如果你使用了类似 FastClick(一个在移动触摸设备上消除 300 毫秒 tap-pause 的工具库),并且你需要添加一些文本标签,那么按钮将不会正常工作,除非设置了 pointer-events: none。
- <label for="file">
- <strong>
- Choose a file
- </strong>
- </label>
- .inputfile + label * { pointer-events: none; }
JavaScript
最后需要做的事情是标识用户选择了哪些文件。原生的文件上传域是有这个功能的,但是这里使用的是虚拟的按钮。特效中使用 javascript 来实现这个功能。
- <input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected"
- multiple />
- var inputs = document.querySelectorAll( '.inputfile' ); Array.prototype.forEach.call(
- inputs, function( input ) { var label = input.nextElementSibling, labelVal
- = label.innerHTML; input.addEventListener( 'change', function( e ) { var
- fileName = ''; if( this.files && this.files.length > 1 ) fileName = ( this.getAttribute(
- 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length
- ); else fileName = e.target.value.split( '\\' ).pop(); if( fileName ) label.querySelector(
- 'span' ).innerHTML = fileName; else label.innerHTML = labelVal; }); });
浏览器禁用 JavaScript 的处理
如果浏览器禁用了 JavaScript,那么只有使用原生的文件上传域组件。我们需要做的事情是在元素上添加一个. no-js 的 class,然后使用 Javascript 来替换它。
.
- <html class="no-js">
- <head>
- <!-- remove this if you use Modernizr -->
- <script>
- (function(e, t, n) {
- var r = e.querySelectorAll("html")[0];
- r.className = r.className.replace(/(^|\s)no-js(\s|$)/, "$1js$2")
- })(document, window, 0);
- </script>
- </head>
- </html>
- js.inputfile {
- width: 0.1px;
- height: 0.1px;
- opacity: 0;
- overflow: hidden;
- position: absolute;
- z - index: -1;
- }
- .no - js.inputfile + label {
- display: none;
- }
来源: http://www.phperz.com/article/17/0708/268904.html