0
点赞
收藏
分享

微信扫一扫

css:隐藏input file标签并触发点击上传文件事件

(目录)

通用的按钮样式

/* button样式来自element-ui */
.button {
color: #fff;
background-color: #409eff;

display: inline-block;
line-height: 1;
white-space: nowrap;
cursor: pointer;

-webkit-appearance: none;
text-align: center;
box-sizing: border-box;
outline: none;
margin: 0;
transition: 0.1s;
font-weight: 500;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
padding: 12px 20px;
font-size: 14px;
border-radius: 4px;
}

.button:hover {
background: #66b1ff;
border-color: #66b1ff;
color: #fff;
}

在这里插入图片描述

方式一:将input标签覆盖到按钮的最上层

通过子绝父相 的定位,将input标签隐藏覆盖到按钮的最上层,不过,发现会出现一个文字提示

在这里插入图片描述

.file-input-wrap {
position: relative;
}

/* 隐藏文件选择 */
.file-input {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
opacity: 0;
font-size: 0;
}
<div class=button file-input-wrap>
<span>上传文件</span>
<input
type=file
class=file-input
/>

</div>

方式二:通过label标签触发点击事件

通过label标签关联input标签,可以触发点击事件

/* 隐藏文件选择 */
.file-input {
display: none;
}
<label
class=button
for=file-input
>

<span>上传文件</span>
<input
type=file
class=file-input
id=file-input
/>

</label>

当然,如果把label中的for属性去了,也是可以直接触发的

<label class=button>
<span>上传文件</span>
<input
type=file
class=file-input
/>

</label>

方式三:js触发文件上传的点击事件

通过js监听按钮点击事件,主动触发文件上传的点击事件

/* 隐藏文件选择 */
.file-input {
display: none;
}
<div
class=button
id=file-input-btn
>

<span>上传文件</span>
</div>

<input
type=file
class=file-input
id=file-input-common
/>


<script>
// 监听按钮点击事件
document
.querySelector('#file-input-btn')
.addEventListener('click', function () {
// 主动触发文件上传点击事件
document.querySelector('#file-input-common').click()
})
</script>

总结

通过比对发现,方式二 是一个不错的选择

参考 Vue触发隐藏input file的方法实例详解 写上传文件时,将html中的<input type="file" />(选择文件) 元素隐藏,并通过其它方式点击触发

举报

相关推荐

0 条评论