模式未打开时隐藏 'close' 个链接

Hide 'close' links when modal is not open

我已经为此工作了几个小时,我试过 vars,我试过隐藏元素,但没有任何效果,而且......很抱歉退出,但我已经 ost down到最后,

问题:: 我有一个基本的 javascript 模态,取自 w3 学校,已根据我的需要稍作改动, https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

我的 javascript 代码如下。

我需要的是,我需要在隐藏弹窗时隐藏CLOSE span,

<span class="close">CLOSE</span> 换句话说,我不希望 close link 一直显示,当模态 os cl[ 时应该隐藏 close link =33=]ed,并在模式打开时显示。

下面是我的代码,我可以得到一个有效的 javascript 示例吗?

如有任何帮助,我们将不胜感激

function closeModal() {
  modal.style.display = "none";
}

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var spans = document.getElementsByClassName("close");
for (let closeBtn of spans) {
  closeBtn.onclick = closeModal;
}

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>```

只需添加适当的 show/hide 函数 hide/show 跨度:

将 closeModal() 更改为:

function closeModal() {
  modal.style.display = "none";
  spans[0].style.display = "block";
}

并将 btn.onclick 更改为:

btn.onclick = function() {
  modal.style.display = "block";
  spans[0].style.display = "none";
}

我看到您正在使用 getElementsByClassName(),它返回(总是)结果数组(这就是为什么我使用索引 ([0]) 来访问找到的元素)。如果我是你,我会在 span 中添加 new id 这样你就可以确定你的目标是什么。

看看Changing HTML style

如果我没理解错的话。 试试这个:

function closeModal() {
  modal.style.display = "none";
  for (let closeBtn of spans) {
    closeBtn.style.display = 'none';
  }
}

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var spans = document.getElementsByClassName("close");
for (let closeBtn of spans) {
  closeBtn.onclick = closeModal;
  closeBtn.style.display = 'none';
}

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";

  for (let closeBtn of spans) {
    closeBtn.style.display = 'inline';
  }
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
    for (let closeBtn of spans) {
      closeBtn.style.display = 'none';
    }
  }
}
</script>```

如果我们把重复的代码放在单独的函数中会更好。