先搭建一个想要效果的页面结构,即:文件名:输入框 上传控件;
然后,将上传控件隐藏,浮动盖在按钮上(注意调整上传控件大小,确保完全覆盖在按钮上)。这样当用户点击按键的时候实际上就是点击的上传控件。
最后,通过dom操作获取选择的文件名(或路径)填入前面的输入框,即可完成上传控件的改造。
获取文件名:
document.getElementById('upload').files[0].name;
获取文件路径:
document.getElementById('upload').value;
原生代码:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<span>文件名:</span>
<input type="text" id="doc">
<button>选择文件</button>
<input type="file" id="upload" onchange="getFile(value)"
style="opacity: 0.5; margin-left: -74px; width: 74px;">
</body>
</html>
<script>
function getFile(value){
var doc = document.getElementById('doc');
var upload = document.getElementById('upload');
var fileName = upload.files[0].name;
var filePath = upload.value;
doc.value = fileName;
console.log(fileName);
console.log(filePath);
</script>
vue代码:
<template>
<span>文件名:</span>
<input type="text" ref="filePath">
<button>选择文件</button>
<input type="file" ref="upload"
name="file" class="upload"
@change="getFileNameToText" multiple="multiplt"
</div>
</template>
<script>
export default {
methods: {
getFileNameToText() {
var fileObj = this.$refs['upload'];
var fileName = fileObj.files[0].name;
var filePath = fileObj.value;
this.$refs['filePath'].value = fileName;
console.log(fileName, 'fileName');
console.log(filePath, 'filePath');
</script>
<style scoped>
.upload {
opacity: 0;
width: 74px;
margin-left: -74px;
</style>
复制代码
- 2097
-
OBKoro1
Angular.js
Vue.js
- 1.2w
-
yeyan1996
JavaScript