我是初学者,我试图重写 CSS 中的 :hover
伪类,如果我悬停的元素位于其他元素下方,则不会让我触发事件.
如果我将鼠标悬停在 div 上,CSS 过渡就会启动,但是,如果我越过在视觉上位于 div 上方的文本,则不会发生任何事情。
我有四个这样的元素,所以我尝试使用 getElementsByClassName 创建要在 JavaScript 中迭代的数组,但控制台总是给我相同的错误
index.html:77 Uncaught TypeError: Cannot read property 'style' of
undefined
at stretchback (index.html:77)
at HTMLParagraphElement.onmouseout (index.html:24)
stretchback @ index.html:77
onmouseout @ index.html:24
<script>
var boxes = document.getElementsByClassName('skill-box');
function stretch() {
for (var i=0; i < boxes.length; i++)
boxes[i].style.opacity = "0.3";
boxes[i].style.transform = "scaleY(10)";
boxes[i].style.borderRadius = "0px";
boxes[i].style.transition = "opacity 2s, transform 2s, border-radius 1s ease-in-out";
}
function stretchback() {
for (var i=0; i < boxes.length; i++)
boxes[i].style.opacity = "1";
boxes[i].style.transform = "scaleY(1)";
boxes[i].style.borderRadius = "10px";
boxes[i].style.transition = "opacity 2s, transform 2s, border-radius 1s ease-in-out"; }
</script>
我做错了什么?
最佳答案
这个非常简单...您在 for
循环中错过了一个左大括号:
for (var i=0; i < box.length; i++) { // <-- for example, here
我使用了 box.length
因为你也已经有了元素数组。
您的原始代码:
function stretch() {
for (var i=0; i < document.getElementsByClassName('skill-boxes').length; i++) // <-- OUCH
box[i].style.opacity = "0.3";
box[i].style.transform = "scaleY(10)";
关于JavaScript 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46798773/