2 回答

TA貢獻1820條經驗 獲得超9個贊
我會從這樣的事情開始。您不需要一堆 javascript 來使一個按鈕以編程方式單擊另一個按鈕。讓一些聰明的 css 完成所有的提升。(我已經用解釋注釋了 css,但如果有任何需要澄清的地方,我很樂意詳細說明。)
這個片段讓你到達一個點,文件輸入的更改會觸發你的函數,并且你有一個對輸入的引用,并通過擴展它的文件和表單。從那里做任何你需要做的事情。
function handleFileChange ({target}) {
if (target.files.length) {
// do something with the form.
// target.form.submit() or whatever
console.log(target.files);
}
}
const fileInput = document.querySelector('input');
fileInput.addEventListener('change', handleFileChange);
form {
/* provides positioning context for the file input (below) */
position: relative;
/* purely cosmetic */
background: #0099ff;
color: white;
font-weight: bold;
font-size: 3rem;
}
form div {
/* purely cosmetic */
padding: 3rem;
text-align: center;
font-family: sans-serif;
/*
allows clicks to pass through the text
element and hit the file input instead
*/
pointer-events: none;
}
input[type=file] {
/* hides the file input while leaving it clickable */
opacity: 0;
/*
positions the file input to occupy the entire
container, so no matter where you click it triggers
the file chooser
*/
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
}
<form>
<input type="file" name="some-file" />
<div>Upload a file</div>
</form>
添加回答
舉報