自定义input file样式

上传图片<input type="file" name="fn">

 

 修改:

<div class="filebutton"><div>上传图片</div><input type="file" name="fn"></div>

现在我们先来改下包裹文字的div样式:

.filebutton div{
    font-size: 25px;
    background: #00ff7f;
    color: white;
    padding: 10px 15px;
}

 

自然,现在点击“上传图片”这块区域是不管用的,现在要做的就是使“选择文件”的响应区域与之重合。
尝试将“选择文件”按钮移入“上传图片”区域:

.filebutton{
    position: relative;
}
.filebutton input{
    position: absolute;
    top: 0;
}

“上传图片”这按钮太长了,理想的状态是使他的宽度随文本长度而变,且我们可以使用padding等属性调整,于是父div里加上display: inline-block

.filebutton{
    position: relative;
    display: inline-block;
}

 

宽度也调整好了,但总不能使用这个样子的按钮吧,

那就将它透明度设置为'0'隐藏起来(opacity: 0;):

.filebutton input{
    position: absolute;
    top: 0;
    opacity: 0;
}

现在看起来似乎没什么问题了,但实际上这个按钮现在的响应区域有很大问题:

 

现在增大input中的font-size来增大响应区域:

.filebutton input{
    position: absolute;
    top: 0;
    opacity: 0;
    font-size: 100px;
}

现在按钮内所有区域都能响应了,但你会发现,按钮外的很大一部分区域也会响应...
注释掉opacity:0来看看现在的真实效果:

.filebutton input{
    position: absolute;
    top: 0;
    /*opacity: 0;*/
    font-size: 100px;
}

 

 

 实际上这句文字所在行才是真正的响应区域,也许你已经有对策了,在父div里设置"overflow:hidden"

.filebutton{
    position: relative;
    display: inline-block;
    overflow: hidden;
}

 

响应区域调整完成。
最后取消掉opacity:0的注释,大功告成! 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一种可能的实现方式如下所示: 1. 创建一个包含样式的CSS类或者ID。 ```css .custom-file-input { position: absolute; /* 使文件选择框覆盖在自定义的按钮之上 */ opacity: 0; /* 隐藏默认的文件选择框 */ z-index: -1; /* 避免文件选择框挡住其他内容 */ } .custom-file-label { /* 自定义样式的文件选择文本 */ background-color: #007bff; color: #fff; border-color: #007bff; } .custom-file-label::after { /* 自定义样式的“选择文件”文本 */ content: '选择文件'; display: inline-block; background-color: #28a745; color: #fff; border-radius: 4px; padding: 6px 12px; cursor: pointer; } ``` 2. 在HTML文件中添加一个文件选择框和一个自定义按钮,使用相同的label标签关联它们。 ```html <label class="custom-file-label" for="customFile">选择文件</label> <input type="file" class="custom-file-input" id="customFile"> ``` 3. 使用JavaScript来监听文件选择框的change事件,当用户选择文件后更新自定义文本框的文本。 ```javascript // 获取文件选择框和自定义文本框 const fileInput = document.getElementById('customFile'); const fileLabel = fileInput.nextElementSibling; // 监听文件选择框的change事件 fileInput.addEventListener('change', function(event) { const fileName = event.target.files[0].name; // 更新自定义文本框的文本 fileLabel.innerText = fileName; }); ``` 这样就实现了一个简单的自定义样式的文件选择框。注意,上述实现方式可能不兼容所有浏览器和操作系统,需要进行相应的兼容性测试和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值