【问题标题】:How to use toggle with a parent class如何在父类中使用切换
【发布时间】:2022-07-20 22:35:45
【问题描述】:

我在实习期间正在学习 JavaScript,我的老板问我:你能不能再尝试一次,但在父 div 上而不是在每个 Rect 上放置一个类? 这是否意味着我必须使用父类来做同样的工作?因为我从今天早上开始就一直在尝试,我不知道该怎么做。

我的代码适合子类:


            const allRects = document.getElementsByClassName("rect"); 

            rect2.addEventListener("click", makeAllRectsSmaller); 

            function makeAllRectsSmaller() {
                for (let index = 0; index < allRects.length; index++) {
                    // console.log(allRects[index]);

                    isBig = allRects[index].classList.contains("bigRect");
                    // console.log(isBig);

                    if (isBig) {
                        console.log(isBig);

                        allRects[index].classList.remove("bigRect");
                        allRects[index].classList.add("smallRect");
                        // console.log(allRects[index]);
                    } else {
                        // Sinon
                        allRects[index].classList.remove("smallRect");
                        allRects[index].classList.add("bigRect");
                        console.log(allRects[index]);
                    }
                }
                
                // console.log(allRects);
            }```

my style and body are like this 

```<style>
            .rect {
                background: grey;
                width: 250px;
                height: 200px;
                margin: 10px;
                float: left;
            }
            .rect.red {
                background: red;
            }
            .rect.blue {
                background: blue;
            }

            .rect.bigRect {
                width: 250px;
                height: 200px;
                margin: 10px;
            }
            .rect.smallRect {
                width: 150px;
                height: 150px;
                margin: 10px;
            }
        </style>
    </head>

    <body>
        <div id="rectjs" class="exoJs">
            <div id="rect1" class="rect red bigRect"></div>
            <div id="rect2" class="rect red bigRect"></div>
            <div id="rect3" class="rect red bigRect"></div>
        </div>```

But i cannot find a way to use parent class instead of child class.

Is someone could help me please ? thank you very much 

【问题讨论】:

    标签: javascript toggle


    【解决方案1】:

    你会在你的 CSS 中做这样的事情:

    .exoJs div {
        /* your CSS  */
    }
    

    这针对父div (.exoJs) 内部的矩形divs。

    【讨论】:

      猜你喜欢
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多