一、第一种实现方式
1.通过一个按钮触发file的click事件;
2.file的click事件触发之后,选择一个文件之后,触发file的onchange事件,给input text文本框复制;
JavaScript:
//浏览文件
function fileBrowse(){
//触发浏览事件
document.forms["fileForm"].upload.click();
}
function setFilePath(){
$("#showFilePath").val(document.forms["fileForm"].upload.value);
}
HTML代码:
<input type="file" id="uploadFile" name="upload" style="display: none;" onchange="setFilePath()"/>
<input id="showFilePath" type="text" style="width:300px;margin:4px;" >
<input name="Browse" value="Browse..." type="button" style="margin-bottom:4px;" class="button" onclick="fileBrowse()"/>
以上做法会引发file文本框的安全问题,从而使得form表单提交不了,采用下面方式最好。
二、第二种实现方式
原理:
把真实的input(file)置透明后放到模拟input(file)的上方,当鼠标移至模拟按钮时触发mouseover事件,通过js使input file 浏览按钮与模拟按钮重合。
然后把真实input(file)里的值取出放到模拟文本框里面。
JavaScript:
function setFilePath(){
$("#showPath").val(document.forms["local_radio"].upload.value);
}
$(function(){
$("#local_button").mouseover(function(e){
$("#uploadFile").show();
var local_button_left = $(this).offset().left;
var local_button_innerWidth = $(this).innerWidth();
var x_ = e.pageX;
var file_left = x_;
var file_innerWidth = $("#uploadFile").innerWidth();
//alert(local_button_left+"-"+local_button_innerWidth+"-"+x_+"-"+$("#uploadFile").innerWidth());
if((x_+file_innerWidth)>(local_button_left+local_button_innerWidth)){
$("#uploadFile").css("left",e.pageX-file_innerWidth);
}else{
$("#uploadFile").css("left",local_button_left-5);
}
});
});
CSS:
<style type="text/css">
.file{
display:none;
width:0px;
height:22px;
position:absolute ;
filter: alpha(opacity = 0);
-moz-opacity:0;
opacity: 0;
z-index: 110;
}
</style>
HTML代码:
<input type="file" id="uploadFile" name="upload" onchange="setFilePath()" class="file"/>
<input type="text" class="textbox140" id="showPath" style="width:300px;" readonly="readonly">
<input type="button" id="local_button" class="button95" value='<s:text name="broker.manager.browse" />'>
转载于:https://my.oschina.net/yonghan/blog/618408