使用自定义的按钮替换默认的<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

 

转载于:https://www.cnblogs.com/liulangmao/p/3547650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值