2016-3-30 (HTML5)
在页面上进行上传文件,大家都会用到 <input type="file"/> 进行文件的上传,但是这么样会出现一个问题,如最简单的文字定制。不能通过value 设置值。
这时候我们我们就遇到了上传按钮优化的问题。
主要思路,给出一个 <input type="text"/>文本输入框 和 <input type="button"/>按钮 两个按钮,分别完成 原来的文字显示(按钮) 与 上传文件路径的显示(文本输入框的功能)。
以下给出两种方式,
方式一:一种通过将 js 写入到HTML属性中
方式二:将js写成javascript 脚本
下面给出参考代码
用到的图片sc
方式一:一种通过将 js 写入到HTML属性中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改默认的文件上传按钮</title>
<style type="text/css">
</style>
</head>
<body>
<!--美化Input tpye="file", 文件上传标签 -->
<input type="text" size="20" name="upfile" id="upfile" readonly style="border:1px dotted #ccc">
<input type="button" onclick="path.click()" style="width:60px; border:1px solid #ccc; background-image:url(img/sc.png); /*background-color: #b3d4fc*/">
<input type="file" id="path" style="display:none" onchange="upfile.value=this.value">
<!--div background-color, background-image 必须设置高, height可以不必设置, 默认width:100% -->
<!-- background-color只会覆盖没有图片的区域或者透明的区域,-->
<div style="height:100px; background:#b3d4fc url(img/sc.png); background-repeat: no-repeat;"></div>
</body>
</html>
效果:
方式二:将js写成javascript 脚本
其中遇到了个问题,貌似span标签在不同的浏览器中,通过纯javascript调用不了onclick属性,望大家知道的话给出解答
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=gb2312" />
<meta http-equiv="content-language" content="zh-cn" />
<meta name="robots" content="all" />
<meta name="keywords" content="关键字描述" />
<meta name="description" content="站点描述" />
<meta name="author" content="我们,we@126.com" />
<meta name="copyright" content="版权所有" />
<title>css+js定义input的file浏览按钮样式兼容FireFox</title>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<style type="text/css">
<!--
*{ margin:0; padding:0; border:0;}
body{font:12px/130% verdana,geneva,arial,helvetica,sans-serif,宋体; padding:20px;}li{list-style:none;}
.clearfix:after{content:" ";display:block;height:0;clear:both;visibility:hidden;}.clearfix{*display:inline-block;}
.text{ border:1px solid #999; height:16px; width:300px; font-family:verdana; font-size:12px;padding-top:2px; float:left; margin-right: 5px;}
.file{ width:67px;overflow:hidden; background:url(img/sc.png); height:22px; *vertical-align:3px; float:left;}
#file{ width:0; height:20px; margin-left:-154px; *margin-left:-3px; filter:alpha(opacity=0); -moz-opacity:.0; opacity:0.0; cursor:pointer;}
-->
</style>
</head>
<body>
<!-- 美化input标签 -->
<input type="text" readonly class="text" id="text"/>
<span class="file" id="fileSpan"><input id="file" type="file" /></span>
<script type="text/javascript">
var file = document.getElementById("file");
var text = document.getElementById("text");
$("#fileSpan").click(function(){
//alert("hahaha");
file.click();
});
file.onchange = type;
function type()
{text.value = file.value;}
</script>
</body>
</html>
效果: