(转)自定义样式的上传文本框

Web上传文件需要用到input标签,type=file的控件,当然,form还要有一个属性enctype="multipart/form-data"

这个input标签的样式是很难修改的,虽然这个标签对应的组件是一个文本框加一个按钮,但你不可能分别修改他们的样式。很巧,之前我们一个项目的web部分,整体界面设计好了,至少比浏览器默认的要好看吧,遗憾的是其中要用到文件上传,这部分显示和整体界面显得和不协调。无奈之下,百度、Google一通搜索,结果是鉴于浏览器安全性,是不运行直接给文件上传文本框赋值的,如果赋值了,是不能提交的,会被清空内容,也就是说隐藏上传文件框,用文本框加按钮,文本框onChange时再给文件上传框赋值是不行的。能做出需要的样式,但根本无法提交表单。

中国人民的智慧是无穷的!搜遍了网络,最后终于找到了解决的办法(好像是华军软件园的一片文章),指导思想是用需要的样式做一个文本框和一个按钮,加入一个上传文件框,宽度设为1(这样基本只剩下“浏览”按钮了),通过滤镜让他变成透明的,定义按钮的鼠标事件,当鼠标从按钮上划过的时候,移动上传文本框,跟随鼠标,这样,当你单击的时候,实际上是点击了上传文本框的“浏览”按钮。自定义带样式的按钮是个摆设,没意义,之前我找到的代码只能在IE下运行(javascript和滤镜定义的兼容性),经过修改后,现在IE和FireFox都可以了,代码如下:

<script>
var isIE = /msie/i.test(navigator.userAgent);
var isFF = /firefox/i.test(navigator.userAgent);
var detlaX,detlaY,ooo;

function beginDrag(me,evt){
 e = evt || window.event;
 ooo = me;
 document.onmousemove = move;
 document.onmouseup = up;
 if(isIE)me.setCapture();  
 if(isFF)window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
}
function move(evt){
  e = evt || window.event;
  document.getElementById("f").style.left = e.clientX - 55 + "px";
  document.getElementById("f").style.top = e.clientY  - 10 + "px";
 }
function up(){
 document.onmousemove = null;
 document.onmouseup = null;
 if(isIE)ooo.releaseCapture();
 if(isFF)window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP);
}
</script>

<body>
<form method=post action="">
<input type="text" name="" id="t1" name="t1">
<input type="button" value=" 选 择 文 件 " onmousemove="beginDrag(this,event);" onmouseout="up()"><br>
<input type="file" id="f" name="f" onchange="t1.value=this.value" style="position:absolute;filter:alpha(opacity=0);-moz-opacity:0;opacity:0;" size="1" hidefocus>
</form>

posted @ 2010-08-12 18:24  arix04  阅读(461)  评论(0编辑  收藏  举报