英文:
Hide element after previewing picture
问题
以下是您提供的内容的翻译部分:
实际上,我正在尝试创建一个表单,用于向画廊添加图片。问题是,添加图片的按钮比预览照片宽,所以当我们添加图片时,按钮会显示在背景中。我要说明我在JavaScript方面是新手。
我尝试了不同的JavaScript方法,但都没有成功。如果有人能告诉我我做错了什么,或者我可以做什么,那将非常棒!
首先,这是预览的代码:
imageInput.onchange = (evt) => {
const [file] = imageInput.files;
if (file) {
preview.src = URL.createObjectURL(file);
}
if (file != null) {
preview.style.display = "block";
}
};
const displayPreview = document.getElementById("hide");
if (file != null) {
displayPreview.style.display = "none";
}
<div id="upload">
<img id="preview" src="#" alt="Votre photo" />
<img
id="img-img"
src="assets/icons/img-vector.svg"
alt="Image d'image"
/>
<div id="hide">
<label class="file-upload">
<input accept="image/*" type="file" id="imageInput" />
+ Ajouter photo
</label>
</div>
<p>jpg, png : 4mo max</p>
</div>
请注意,这是提供的JavaScript和HTML代码的翻译部分,不包括代码本身。
英文:
Actually I'm trying to make a form to add pictures to a gallery. The thing is, the button to add picture is wider than the preview photo so when we add the picture, we have the button in the background. I precise that I'm new in Javascript.
I've tried different ways with JS but none of them are working. If someone can tell me what did I do wrong or what I can do, it will be super great !
First here is the code for the preview :
imageInput.onchange = (evt) => {
const = imageInput.files;
if (file) {
preview.src = URL.createObjectURL(file);
}
if (file != null) {
preview.style.display = "block";
}
};
const displayPreview = document.getElementById("hide");
if (file != null) {
displayPreview.style.display = "none";
}
<div id="upload">
<img id="preview" src="#" alt="Votre photo" />
<img
id="img-img"
src="assets/icons/img-vector.svg"
alt="Image d'image"
/>
<div id="hide">
<label class="file-upload">
<input accept="image/*" type="file" id="imageInput" />
+ Ajouter photo
</label>
</div>
<p>jpg, png : 4mo max</p>
</div>
答案1
得分: 0
你需要将隐藏 displayPreview 块的代码行移动到事件处理程序内部。如果保持在外部像这样,它将不起作用。
你需要做类似于下面的操作。
const displayPreview = document.getElementById("hide");
imageInput.onchange = (evt) => {
const [file] = imageInput.files;
if (file) {
preview.src = URL.createObjectURL(file);
}
if (file != null) {
displayPreview.style.display = "none";
preview.style.display = "block";
}
};
希望这有所帮助。
英文:
You need to move the line which hides displayPreview block inside the event handler. By keeping it outside like that it would not work.
you need to do something like this below.
const displayPreview = document.getElementById("hide");
imageInput.onchange = (evt) => {
const = imageInput.files;
if (file) {
preview.src = URL.createObjectURL(file);
}
if (file != null) {
displayPreview.style.display = "none";
preview.style.display = "block";
}
};
I hope this help.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论