วิธีแก้ปัญหาการทำงาน
ให้ฉันเพิ่มในโพสต์เก่านี้เป็นวิธีแก้ปัญหาการทำงานที่ฉันเคยใช้ที่ทำงานใน 80% หรือมากกว่าเบราว์เซอร์ทั้งหมดทั้งเก่าและใหม่
การแก้ปัญหานั้นซับซ้อน แต่ก็ง่าย ขั้นตอนแรกคือการใช้ประโยชน์จาก CSS และคาดเดาชนิดของไฟล์อินพุตด้วย "องค์ประกอบใต้" ที่แสดงผ่านเนื่องจากมีความทึบของ 0 ขั้นตอนต่อไปคือการใช้ JavaScript เพื่ออัปเดตป้ายกำกับตามต้องการ
HTML รหัสจะถูกแทรกเพียงถ้าคุณต้องการวิธีที่รวดเร็วในการเข้าถึงองค์ประกอบที่เฉพาะเจาะจง แต่ชั้นเรียนเป็นสิ่งที่จำเป็นเพราะเกี่ยวข้องกับ CSS ที่กำหนดกระบวนการทั้งหมดนี้ขึ้น
<div class="file-input wrapper">
<input id="inpFile0" type="file" class="file-input control" />
<div class="file-input content">
<label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
<input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
</div>
</div>
CSS โปรดจำไว้ว่าการระบายสีและรูปแบบตัวอักษรนั้นเป็นสิ่งที่คุณต้องการอย่างสมบูรณ์หากคุณใช้ CSS พื้นฐานนี้คุณสามารถใช้เครื่องหมายหลังเลิกงานตามสไตล์ได้ตามที่คุณต้องการ
.file-test-area {
border: 1px solid;
margin: .5em;
padding: 1em;
}
.file-input {
cursor: pointer !important;
}
.file-input * {
cursor: pointer !important;
display: inline-block;
}
.file-input.wrapper {
display: inline-block;
font-size: 14px;
height: auto;
overflow: hidden;
position: relative;
width: auto;
}
.file-input.control {
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
height: 100%;
position: absolute;
text-align: right;
width: 100%;
z-index: 2;
}
.file-input.content {
position: relative;
top: 0px;
left: 0px;
z-index: 1;
}
.file-input.output {
background-color: #FFC;
font-size: .8em;
padding: .2em .2em .2em .4em;
text-align: center;
width: 10em;
}
.file-input.button {
border: none;
font-weight: bold;
margin-left: .25em;
padding: 0 .25em;
}
JavaScript บริสุทธิ์และเป็นจริง แต่เบราว์เซอร์ OLDER (เกษียณอายุ) บางตัวอาจยังมีปัญหากับมัน (เช่น Netscrape 2!)
var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
if (inp[i].type != 'file') continue;
inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
inp[i].onchange /*= inp[i].onmouseout*/ = function () {
this.relatedElement.innerHTML = this.value;
};
};