[英]JavaScript loop doesn't work
我是一個初學者,我想覆蓋一下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)";
似乎是一個范圍界定問題。 嘗試在拉伸和拉伸函數中移動框和技能變量聲明。
如何使用addEventListener('mouseenter')而不是將css懸停。
您可能想要避免變量被覆蓋,如下所示。 如果下面的代碼有幫助,請詳細說明
function stretch() { // maybe call this expand?
var boxes = document.getElementsByClassName('skill-boxes');
var skills = document.getElementsByClassName('para');
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() { // maye call this shrink?
var boxes = document.getElementsByClassName('skill-boxes');
var skills = document.getElementsByClassName('para');
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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.