![](/img/trans.png)
[英]My javascript function is working partially/ not working properly
[英]My javascript function is not working properly
我正在做一個網站項目。
我在 w3schools 中看到了用於圖像的 animation。
我已經試過了,它只適用於一張照片——
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal
var img = document.getElementById('a');
var modalImg = document.getElementById("img01");
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
但我想將它用於多個圖像。
所以我創建了一個 function 像這樣:
function myBeautifulFunc(imageId, modalImageId) {
var modal = document.getElementById('myModal');
var img = document.getElementById(imageId);
var modalImg = document.getElementById(modalImageId);
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
}
並稱之為 function:
myBeautifulFunc('a', 'img01')
結果是:
它適用於第一張圖片,但是當我在第二張嘗試時,
它看起來像這樣: https://ibb.co/Mk8Xw1Z
當我點擊它時,我只想顯示一張圖片,
但它顯示了兩個圖像。
我怎么解決這個問題?
您關閉的 function span.onclick = function()
沒有隱藏子項,因此第二次單擊時,您會看到上次單擊時的上一個圖像和 modalImage 。
function myBeautifulFunc(imageId, modalImageId) {
var modal = document.getElementById('myModal');
var img = document.getElementById(imageId);
var modalImg = document.getElementById(modalImageId);
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
img.style.display = "none" // hide this also
modalImg.style.display = "none" // hide this also
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.