Javascript 为什么调用document.getElementsByClassName时我的函数返回undefined?

Javascript 为什么调用document.getElementsByClassName时我的函数返回undefined?,javascript,css,Javascript,Css,我正在尝试使用css/JavaScript创建一个简单的开关。下面你可以看到我在打电话 document.getElementsByClassName('onOffSwitch').style.animation = 'off'; js还需要什么代码来理解我所说的名为“onOffSwitch”的div?我想知道为什么当前代码集不起作用,以及如何修复它。getElementsByClassName()返回集合。指定索引,如下所示 document.getElementsByClassName(

我正在尝试使用css/JavaScript创建一个简单的开关。下面你可以看到我在打电话

document.getElementsByClassName('onOffSwitch').style.animation = 'off';


js还需要什么代码来理解我所说的名为“onOffSwitch”的div?我想知道为什么当前代码集不起作用,以及如何修复它。

getElementsByClassName()
返回集合。指定
索引
,如下所示

document.getElementsByClassName('onOffSwitch')[0].style.animation = 'off';

因为
.getElementsByClassName()
返回一个(集合)元素,并且您正在尝试设置集合的样式,而不是集合中的一个元素:

// Change the animation style of the first element with the class "onOffSwitch"
document.getElementsByClassName('onOffSwitch')[0].style.animation = 'off';
另外,由于
.getElementsByCassName()
返回一个“活动”节点列表(每次使用分配给该列表的变量时都会更新该列表),因此它确实会影响性能。在大多数情况下,静态节点列表更好,您可以通过以下方式获得:

document.querySelectorAll(".onOffSwitch");
但是,同样的规则也适用。那是一个完整的收藏。您需要访问集合中的各个元素才能使用它们的属性

现在,看看你的代码,你根本不想要一个集合。您只有一个
div class=“onOffSwitch”
,因此您可以通过以下方式获得该元素:

document.querySelector("div.onOffSwitch");
然后你可以直接使用它

let state={
切换:“开”,
位:[0,1,0,1]
};
//获取对div的引用
var divSwitch=document.querySelector('div.onOffSwitch');
//设置事件处理程序
divSwitch.addEventListener(“单击”,flipSwitch);
功能翻转开关(){
如果(state.switchG=='On'){
state.switchG='Off';
console.log(state.switchG);
divSwitch.style.animation='off1s1';
}否则{
state.switchG='On';
console.log(state.switchG);
divSwitch.style.animation='on 1s 1';
}
}
.onOffSwitch{
背景色:#4dc71f;
边界半径:5px;
位置:绝对位置;
左:40%;
高度:20px;
宽度:55px;
溢出:隐藏;
文本对齐:居中;
光标:指针;
}
@关键帧关闭{
0%{背景色:绿色;}
100%{背景色:红色;}
}
@上的关键帧{
0%{背景色:红色;}
100%{背景色:绿色;}
}

@Ghoyos上,您没有完全正确设置动画。请参阅我的最新答案。