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

问题描述 投票:0回答:2

[我已经工作了几个小时,我已经尝试了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>```
javascript html modal-dialog popup
2个回答
1
投票

如果我理解正确,试试这个:

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

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


1
投票

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

将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
© www.soinside.com 2019 - 2024. All rights reserved.