带CSS和CSS的自定义上传按钮JavaScript的

时间:2014-04-12 11:31:30

标签: javascript html css

我正在尝试编写自定义上传按钮。我已经隐藏了常规版本,然后将带有图像背景的div放在顶部。

它的效果很好但是我希望在用户选择文件后用文件名填充下面的(禁用的)输入字段,但它不起作用。

JavaScript的:

document.getElementById("upload_button").onchange = function () {
document.getElementById("upload_file").value = this.value;
};

HTML:

<div id="Form_FileInput_Container"><input type="file" id="upload_button" /></div>
<input class="Form_Input" id="upload_file" placeholder="Choose File" disabled="disabled" />

CSS:

#Form_FileInput_Container { position: relative; width: 100px; height: 100px; background: #e5e5e5 url('path/to/upload/image/forms_upload.png') no-repeat; border: 1px solid #cccccc; }
#Form_FileInput_Container input { filter: alpha(opacity=0); opacity: 0; width: 100px; height: 100px; }

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:4)

确保在元素存在后附加 JavaScript

<input id="foo" type="file" />
<input id="bar" type="text" placeholder="Choose File" disabled />
// after elements exist
var foo = document.getElementById('foo'),
    bar = document.getElementById('bar');

foo.addEventListener('change', function () {
    var slash = this.value.lastIndexOf('\\');
    bar.value = this.value.slice(slash + 1);
});

DEMO

答案 1 :(得分:0)

HTML:

<input type="file" id="upload_button" onchange="cutomButton()" /> 

JS:

function customButton() {
    var z=document.getElementById("upload_button").value;
    document.getElementById("upload_file").value = z;
    alert(document.getElementById("upload_file").value);
}