document.getElementById 无法选择多个元素

2023-12-22

我正在努力加载。我有div#loading这是可见的。还有更多div#message哪些是隐藏的。我有js功能。

function loading() {
     setTimeout(function() {
         document.getElementById("loading").style.display = "none";
         document.getElementById("message").style.display = "block";
     }, 500, "fadeOut");
 }

但那一排document.getElementById("message").style.display = "block";仅选择第一个 div#message.

function loading() {
  setTimeout(function() {
    document.getElementById("loading").style.display = "none";
    document.getElementById("message").style.display = "block";
  }, 500, "fadeOut");
}
loading();
#loading {
  display: block;
}
#message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="messages" onload="loading();">
  <div id="loading">
    ...
  </div>
  <div id="message">
    QWERTY
  </div>
  <div id="message">
    123456
  </div>
</div>

正如其他人提到的ids 是唯一的,并且只能在页面上使用一次,因此请使用类。这里我用过querySelectorAll https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll获取类的静态列表。

另一个问题是,您似乎试图使用 jQuery 淡出元素,但您没有将 jQuery 用于其他任何用途。我会建议你使用 CSS 转换。它们易于使用,并且您无需加载庞大的库。这里我添加新的类fadein and fadeout它(根据您的代码)在三秒内将指定元素的不透明度增加/减少到零。

function loading() {
  setTimeout(function() {

    // use a class for the loader too otherwise the transition
    // won't work properly
    const loader = document.querySelector('.loading');
    loader.classList.add('fadeout');

    // grab the elements with the message class
    const messages = document.querySelectorAll('.message');

    // loop over them and add a fadeout class to each
    [...messages].forEach(message => message.classList.add('fadein'));
  }, 500);
}

loading();
.loading {
  opacity: 1;
}

.message {
  opacity: 0;
}

.fadein {
  transition: opacity 3s ease-in-out;
  opacity: 1;
}

.fadeout {
  transition: opacity 3s ease-in-out;
  opacity: 0;
}
<div class="messages">
  <div class="loading">
    Loading
  </div>
  <div class="message">
    QWERTY
  </div>
  <div class="message">
    123456
  </div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

document.getElementById 无法选择多个元素 的相关文章

随机推荐