您的位置:首页 > 其它

使用自定义的按钮替换默认的<input type='file'>

2014-02-13 12:47 218 查看
可以通过让默认的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: