感谢您查看我的问题。我下面有一个带有文件输入字段的表单。可以肯定地说,我已经隐藏了此输入字段,现在使用标签作为主要“按钮”来选择文件。一旦用户单击“上传图片...”标签,我希望标签内的文本从“上传图片...”更改为文件名。我正在遵循下面的本教程,但是(在教程中)编写的 javascript 是为了用户能够选择多个文件。我只允许我的用户选择一个文件。这是一个更改您的个人资料图片页面,以便让您了解此表单的用途。
这是代码:
<!-- Change Picture Form -->
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
这是教程:
http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/
有人可以帮我解释一下我必须做什么吗?我正在考虑事件监听器的一些事情,但我不确定 javascript。我是一名后端开发人员,对 javascript 知之甚少。我不想使用 JQUERY。仅限直接 JavaScript。
再次感谢 StackOverflow 成员(member)的帮助! :D
编辑: 有人说文本已经在改变。这不是......我想要改变标签文本。 “文件输入”标签有两个部分。按钮以及按钮旁边的文本。我使用以下 SASS 代码隐藏了输入标签。这样,仅显示“上传图片...”标签文本。请确保将此 SASS 代码添加到您的文件中,以便您可以看到 LABEL 文本不会更改。
.inputfile
width: 0.1px
height: 0.1px
opacity: 0
overflow: hidden
position: absolute
z-index: -1
最佳答案
您可以使用 JavaScript onchange
事件来检测 #profilepic
input
的值何时发生更改。
此时,您可以捕获 #profilepic
input
的新值
,并用该替换标签文本>值
。
示例:
var profilePic = document.getElementById('profilepic'); /* finds the input */
function changeLabelText() {
var profilePicValue = profilePic.value; /* gets the filepath and filename from the input */
var fileNameStart = profilePicValue.lastIndexOf('\\'); /* finds the end of the filepath */
profilePicValue = profilePicValue.substr(fileNameStart + 1); /* isolates the filename */
var profilePicLabelText = document.querySelector('label[for="profilepic"]').childNodes[2]; /* finds the label text */
if (profilePicValue !== '') {
profilePicLabelText.textContent = profilePicValue; /* changes the label text */
}
}
profilePic.addEventListener('change',changeLabelText,false); /* runs the function whenever the filename in the input is changed */
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
关于javascript - 使用 Javascript 选择文件后如何更改 HTML 标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38818814/