我正在加载。我有可见的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>
答案 0 :(得分:2)
您需要为DOM元素使用唯一的ID。尝试像这样修改代码:
<script type="text/javascript">
function loading() {
setTimeout(function() {
document.getElementById("loading").style.display = "none";
var el = document.getElementsByClassName('message');
console.log(el);
$.each(el, function(i, item){
item.style.display = 'block';
});
}, 500, "fadeOut");
}
loading();
</script>
<style>
#loading {
display: block;
}
.message{
display: none;
}
</style>
<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 class="message">
QWERTY
</div>
<div class="message">
123456
</div>
</div>
答案 1 :(得分:2)
正如其他人所提到的,id
是唯一的,并且只能在页面上使用一次,因此请使用类。在这里,我使用querySelectorAll
来获取静态的类列表。
另一个问题是,您似乎正在尝试使用jQuery淡出元素,但您没有将jQuery用于其他任何东西。我将建议您使用CSS过渡。它们易于使用,并且您无需加载庞大的库。在这里,我添加了新类fadein
和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>
答案 2 :(得分:1)
ID
属性必须是唯一的。您不能在页面上多次使用相同的ID。如果您想使用相同的密钥,则可以将其用作class
或data-id
,它们可以相同或不同。
答案 3 :(得分:1)
您不能在文档中两次使用相同的id来选择多个元素,这些元素按同一Class(而不是id)分组,然后使用以下内容将它们全部选中。
document.querySelectorAll(".ClassName")
或
document.getElementsByClassName(".ClassName");
请注意,这两种方法均以NodeList对象的形式返回文档中具有指定类名的所有元素的集合。
答案 4 :(得分:-1)
课程ID是唯一的
您可以使用jquery及其选择器
您可以选择具有类名或标签名的元素以获取元素数组