[英]Add class when using getElementById
I have an element which I need to hide after a few seconds but this element only needs to be hidden in this particular instance so I am trying to add an Id
to the element.我有一个元素,我需要在几秒钟后隐藏它,但是这个元素只需要隐藏在这个特定的实例中,所以我试图向元素添加一个
Id
。 Problem is that my JS is only applying CSS class to the element if I getElementsByClassName
.问题是,如果我
getElementsByClassName
,我的 JS 只会将 CSS 类应用于元素。
The element:元素:
<div id="main-messages" class="alert alert-{{ message.tags }}">
The JS: JS:
var m = document.getElementById("main-messages");
setTimeout(function(){
if (m && m.length) {
m[0].classList.add('hide');
}
}, 3000);
The CSS: CSS:
.alert {
positition: relative;
opacity: 1;
visibility: visible;
transform: translateX(0px);
transition: .5s ease-out
margin-bottom: 0;
}
.alert.hide {
visibility: hidden !important;
opacity: 0;
transform: translateX(0px);
transition: visibility 0s 2s, opacity 2s linear;
}
I have also tried to create the CSS element by Id and add the .hide
class to it but that did not work.. eg #main-messages.hide{
我还尝试通过 Id 创建 CSS 元素并将
.hide
类添加到它,但这不起作用.. 例如#main-messages.hide{
getElementById
returns a single element, but not nodeList. getElementById
返回单个元素,但不返回 nodeList。
In your code, m.length
is always undefined (false), and m[0]
as well.在您的代码中,
m.length
始终未定义 (false),并且m[0]
也是如此。 You must add class to a single element, without index:您必须将类添加到单个元素,没有索引:
var m = document.getElementById("main-messages"); setTimeout(function() { if (m) { m.classList.add('hide'); } }, 3000);
.alert.hide::after { content: "I'm hidden... really!"; color: red; }
<div id="main-messages" class="alert">test... </div>
Ps typo .alert {positition
→ position *) Ps 错别字
.alert {positition
→ 位置 *)
document.getElementById() only returns one element not an array. document.getElementById() 只返回一个元素而不是数组。
If you change this如果你改变这个
if (m && m.length) {
m[0].classList.add('hide');
}
to到
m.classList.add("hide");
does it work then?那么它有效吗?
It may help.它可能会有所帮助。
window.addEventListener('load', function() { setTimeout(function(){ document.getElementById("main-messages").style.display = "none"; }, 3000); })
<div id="main-messages" class="alert alert-{{ message.tags }}">Hiiiii</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.