为了账号安全,请及时绑定邮箱和手机立即绑定

使用 getElementsByClassName 打开模式不起作用

使用 getElementsByClassName 打开模式不起作用

沧海一幻觉 2023-10-24 20:27:27
我的网站中有一个模式。我需要在我的所有页面中使用该模式。所以我不能在模态脚本中使用 ID。这是我的js代码var modal = document.getElementById('demo-modal');var btn = document.getElementById('open-modal');var close = modal.getElementsByClassName('close')[0];btn.onclick = function() {  modal.style.display = 'block';};close.onclick = function() {  modal.style.display = 'none';};window.onclick = function(event) {  if (event.target == modal) {    modal.style.display = 'none';  }};然后我将上面的 getElementById 更改为 getElementsByClassName ,并且我的 html 将 ID 更改为类,但它根本不起作用。var modal = document.getElementsByClassName('demo-modal');var btn = document.getElementsByClassName('open-modal');var close = modal.getElementsByClassName('close')[0];这是小提琴。有任何想法吗?
查看完整描述

1 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

干得好:

getElementsByClassName行为不同于getElementById. getElementsByClassName:这将返回具有指定类名的元素的子元素的集合,作为 NodeList 对象。

var modal = document.getElementsByClassName('modal')[0];

var btn = document.getElementsByClassName('open-modal')[0];

var close = modal.getElementsByClassName('close')[0];




btn.onclick = function() {

  modal.style.display = 'block';

};


close.onclick = function() {

  modal.style.display = 'none';

};


window.onclick = function(event) {

  if (event.target == modal) {

    modal.style.display = 'none';

  }

};

.modal {

  display: none;

  position: fixed;

  top: 0;

  right: 0;

  bottom: 0;

  left: 0;

  overflow: auto;

  background: rgba(0, 0, 0, 0.8);

  z-index: 99999;

  animation-name: show;

  animation-duration: 0.5s

}


.modal-content {

  position: relative;

  background-color: #fff;

  margin: 10% auto;

  border: 1px solid #888;

  width: 80%;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);

}


@keyframes show {

  0% {

    display: none;

    opacity: 0;

  }

  100% {

    display: block;

    opacity: 1;

  }

}


.modal-header {

  padding: 12px;

  background-color: grey;

  color: white;

}


.modal-body {

  padding: 12px;

}


.modal-footer {

  position: relative;

  background-color: #fefefe;

  margin: auto;

  padding: 12px;

}


.close {

  color: #aaa;

  float: right;

  font-size: 16px;

}


.close:hover,

.close:focus {

  color: black;

  cursor: pointer;

}

<button class="open-modal" name="open-modal-btn">Open Modal</button>


<div class="modal demo-modal">

  <div class="modal-content">

    <div class="modal-header">

      <span class='close'>X</span>

      <h2>Modal Header</h2>

    </div>

    <div class="modal-body">

      <p>Some text in the Modal Body</p>

      <p>Some other text...</p>

    </div>

    <div class="modal-footer">

      <h3>Modal Footer</h3>

    </div>

  </div>

</div>


查看完整回答
反对 回复 2023-10-24
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信