当我按下按钮时,文本框不会更新

时间:2014-08-24 13:43:57

标签: javascript html css dom

我在这里有例子:code example

HTML code:

<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="file-upload btn btn-primary">
    <span>Upload</span> 
    <br> 
    <input id="uploadBtn" class="upload" type="file">
</div>

CSS代码:

.btn {
    border: 1px solid transparent;
    border-radius: 4px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    font-weight: normal;
    line-height: 1.42857;
    margin-bottom: 0;
    padding: 6px 12px;
    text-align: center;
    vertical-align: middle;
    white-space: nowrap;
}

.file-upload input.upload {
    cursor: pointer;
    font-size: 20px;
    margin: 0;
    opacity: 0;
    padding: 0;
    position: absolute;
    right: 0;
    top: 0;
}

.file-upload {
    margin-left: 10px;
    overflow: hidden;
    position: relative;
}
.btn-primary {
    background-color: #428bca;
    border-color: #357ebd;
    color: #fff;
}

JavaScript代码:

document.getElementById("uploadBtn").onchange = function () {
    document.getElementById("uploadFile").value = this.value;
};

在JSFiddle网站中,当我按下上传按钮时,文本框会更新, 但是当我将代码复制到文件,并在Firefox Mozilla下运行时, 文本框不会更新。

我参考了这个网站:How to Style a HTML file upload button in Pure CSS

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

由于在尝试添加uploadBtn侦听器时未创建onchange,因此您的JS无效。尝试等待窗口加载。

window.onload = function() {
   document.getElementById("uploadBtn").onchange = function () {
      document.getElementById("uploadFile").value = this.value;
   };
};