简体   繁体   English

针对特定行使手风琴箭头在香草 JS 中旋转

[英]Targeting an specific row to make an accordion arrow spin in vanilla JS

Hi im working on animating an arrow in an accordion but it only animates the first row no matter which one i pick.嗨,我正在为手风琴中的箭头制作动画,但无论我选择哪一个,它都只会为第一行制作动画。 I know its a target issue but can make this work.我知道这是一个目标问题,但可以解决这个问题。 some help would be great!!一些帮助会很棒!

code pen here https://codepen.io/al-web-dev/pen/bGRXdyL代码笔在这里https://codepen.io/al-web-dev/pen/bGRXdyL

<div class="myDiv">
            <div class="row">
                <div class="col-4">Test</div>
                <div class="col-4 cheese">test 1</div>
                <div class="col-4">
                    <i class="fa fa-arrow-up" aria-hidden="true"></i>
                </div>
            </div>
            <div class="row">
                <div class="col-4">Test</div>
                <div class="col-4 cheese">test 2</div>
                <div class="col-4">
                    <i class="fa fa-arrow-up" aria-hidden="true"></i>
                </div>
            </div>
        </div>


   var myDiv = document.getElementsByClassName("row");

for (var i = 0; i < myDiv.length; i++) {
    myDiv[i].addEventListener("click", function (event) {
        let toggleAble = document.querySelector(".fa-arrow-up");
        let cheese = document.querySelector(".cheese");
        event.target.classList.toggle("yello");
        event.target.classList.toggle("arrow-down");
    });
}

The code in your codepen and your example given here is different.您的代码笔中的代码与此处给出的示例不同。 I suggest settling on one version of the code if you're gonna ask for help.如果您要寻求帮助,我建议您选择一个版本的代码。

The problem you were facing in your codepen example had to do with var toggleAble .您在代码笔示例中遇到的问题与var toggleAble You were query-selecting by a classname.您正在按类名进行查询选择。 .querySelector will only pick the first element from a list of elements it finds. .querySelector只会从它找到的元素列表中选择第一个元素。 That is why you've had only the first arrow react.这就是为什么你只有第一个箭头反应。 Change document before your query selector method to myDiv[i] - the element you're looking for the arrow in. Like so:将查询选择器方法之前的document更改为myDiv[i] - 您要在其中查找箭头的元素。像这样:

 for (let i = 0; i < myDiv.length; i++) { myDiv[i].addEventListener("click", function (event) { var toggleAble = myDiv[i].querySelector(".fa-arrow-up"); toggleAble.classList.toggle("arrow-down"); }); }

Oh and for some reason you've renamed the function parameter to myDiv , an already declared array of elements.哦,出于某种原因,您已将 function 参数重命名为myDiv ,这是一个已声明的元素数组。 I've changed it back to event for you.我已为您将其改回event

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM