使用 getElementsByClassName 打开模式不起作用

我的网站上有一个模式。我需要在我的所有页面中使用该模式。所以我不能在模态脚本中使用 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];

这是小提琴。有任何想法吗?


繁花不似锦
浏览 149回答 1
1回答

智慧大石

干得好: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() {&nbsp; modal.style.display = 'block';};close.onclick = function() {&nbsp; modal.style.display = 'none';};window.onclick = function(event) {&nbsp; if (event.target == modal) {&nbsp; &nbsp; modal.style.display = 'none';&nbsp; }};.modal {&nbsp; display: none;&nbsp; position: fixed;&nbsp; top: 0;&nbsp; right: 0;&nbsp; bottom: 0;&nbsp; left: 0;&nbsp; overflow: auto;&nbsp; background: rgba(0, 0, 0, 0.8);&nbsp; z-index: 99999;&nbsp; animation-name: show;&nbsp; animation-duration: 0.5s}.modal-content {&nbsp; position: relative;&nbsp; background-color: #fff;&nbsp; margin: 10% auto;&nbsp; border: 1px solid #888;&nbsp; width: 80%;&nbsp; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);}@keyframes show {&nbsp; 0% {&nbsp; &nbsp; display: none;&nbsp; &nbsp; opacity: 0;&nbsp; }&nbsp; 100% {&nbsp; &nbsp; display: block;&nbsp; &nbsp; opacity: 1;&nbsp; }}.modal-header {&nbsp; padding: 12px;&nbsp; background-color: grey;&nbsp; color: white;}.modal-body {&nbsp; padding: 12px;}.modal-footer {&nbsp; position: relative;&nbsp; background-color: #fefefe;&nbsp; margin: auto;&nbsp; padding: 12px;}.close {&nbsp; color: #aaa;&nbsp; float: right;&nbsp; font-size: 16px;}.close:hover,.close:focus {&nbsp; color: black;&nbsp; cursor: pointer;}<button class="open-modal" name="open-modal-btn">Open Modal</button><div class="modal demo-modal">&nbsp; <div class="modal-content">&nbsp; &nbsp; <div class="modal-header">&nbsp; &nbsp; &nbsp; <span class='close'>X</span>&nbsp; &nbsp; &nbsp; <h2>Modal Header</h2>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="modal-body">&nbsp; &nbsp; &nbsp; <p>Some text in the Modal Body</p>&nbsp; &nbsp; &nbsp; <p>Some other text...</p>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="modal-footer">&nbsp; &nbsp; &nbsp; <h3>Modal Footer</h3>&nbsp; &nbsp; </div>&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript