在模式未打开时隐藏“关闭”链接

时间:2020-01-19 19:50:51

标签: javascript html modal-dialog popup

我已经工作了几个小时,我已经尝试了vars,我尝试了隐藏元素,并且没有任何效果,并且..并且为退出而感到抱歉,但是我快要结束了,

问题::我有一个基本的javascript模式,该模式取自w3学校,根据我的需要进行了一些更改, https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

我的JavaScript代码在下面。

我需要的是,当模式弹出框被隐藏时,我需要隐藏CLOSE跨度,

<span class="close">CLOSE</span> 换句话说,我不想一直显示关闭链接,应该在模式os关闭时隐藏关闭链接,而在模式打开时显示关闭链接。

下面是我的代码,请给我一个可行的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>```

2 个答案:

答案 0 :(得分:2)

只需将适当的隐藏/显示跨度添加到您的显示/隐藏功能中即可:

将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])来访问找到的元素)。如果您是我,则将新的 id 添加到跨度中,以便确定您要定位的目标。

看看Changing HTML style

答案 1 :(得分:2)

如果我对您的理解正确。 试试这个:

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>```

最好将重复的代码放在单独的函数中。

相关问题