使用自定义的按钮替换默认的

时间:2023-03-09 16:27:30
使用自定义的按钮替换默认的<input type='file'>

可以通过让默认的input type = 'file'按钮透明度变为0,并且让它刚好覆盖在自定义的按钮上,来实现此效果:

将它写成一个jQuery插件:

(function($){
$.fn.browseElement = function(){
var input = $("<input type='file' multiple>"); input.css({
"position": "absolute",
"z-index": 2,
"cursor": "pointer",
"-moz-opacity": "0",
"filter": "alpha(opacity: 0)",
"opacity": "0"
}); input.mouseout(function(){
input.detach();
}); $(this).mouseover(function(){
input.css($(this).offset());
input.width($(this).outerWidth());
input.height($(this).outerHeight());
$("body").append(input);
}); return input;
};
})(jQuery);

注意: 使用input.offset($(this).offset),会产生bug,常常出现两倍的左侧距离,还是使用.css方法

然后在页面中自定义一个上传按钮:

#attach {
width:100px;
height:30px;
border:1px solid #00B7FF;
background:#cae2fd;
border-radius:4px;
color:#00B7FF;
font-size:12px;
line-height:30px;
text-align:center;
margin:auto;
padding:0
}
<div id="attach">选择文件</div>

然后对该按钮调用扩展的browseElement方法:

var hiddenInput = $('#attach').browseElement();

hiddenInput.change(function(){
//上传文件时相关处理代码
});

完整代码在:

http://pan.baidu.com/s/1mgwQpew