【问题标题】:How to use two different transitions for toggling a class?如何使用两种不同的转换来切换课程?
【发布时间】:2020-09-01 13:55:00
【问题描述】:

所以我有一个自定义的可扩展选择。我想应用两种不同的过渡,一种用于打开选择,另一种用于关闭选择。

.select-generic-2 {
  max-height: 39px;
  overflow: hidden;
  z-index: 2;
  transition: z-index 0s, max-height .25s ease-in-out 0s;
}
.select-generic-2.expanded {
  z-index: 3;
  max-height:1000px;
  transition: max-height .25s ease-in-out 0s, z-index 0s .25s;
}

这是我的自定义选择的 HTML 结构

            <span class="select-generic-2 shadow-input">
                <input type="radio" name="status" value="3" id="3">
                <label for="3">text</label>
                <input type="radio" name="status" value="4" id="4">
                <label for="3">text2</label>
            </span>

我正在用 JS 切换 .expanded 类,但总是执行第一个转换属性。我想以这种方式更改 z-index 以避免与具有相同 .select-generic-2 类的其他元素重叠(一次只有一个元素具有 .expanded 类)。任何建议都将非常受欢迎!

编辑:我刚刚意识到问题是不同的,并且与转换无关。只是每个选择的默认 z-index 值为 2,当删除 .expanded 类时,位于折叠下方的选择框会出现在其上方,因为它们具有相同的 z-index (2) 并放在折叠 (位于代码上方)由浏览器访问。

【问题讨论】:

  • 您是否希望通过过渡 z-index 淡化?
  • 不,没有褪色。
  • 可以包含h​​tml代码吗?
  • 是的,我刚刚包含了它

标签: html css transition


【解决方案1】:

由于您要切换 .expnaded 类,请单独使用该类,然后使用您的 JS 在“切换”上添加或删除该类。

.select-generic-2 {max-height: 39px; overflow: hidden; z-index: 2; transition: z-index 0s, max-height .25s ease-in-out 0s;}
.expanded {z-index: 3; max-height:1000px; transition: max-height .25s ease-in-out 0s, z-index 0s .25s;}

然后在 'toggle' 上,从 DOM 中获取元素并使用添加类 '.expanded'

添加类:https://www.w3schools.com/howto/howto_js_add_class.asp 删除类:https://www.w3schools.com/howto/howto_js_remove_class.asp

【讨论】:

  • 我刚刚意识到问题是不同的,并且与转换无关。只是每个选择的默认 z-index 值为 2,当删除 .expanded 类时,折叠下的选择框会出现在它上面,因为它们具有相同的 z-index (2) 并放在折叠上(其中位于它们上方的代码中)由浏览器访问。
【解决方案2】:

伙计们,我刚刚添加了一个名为 .collapsing 的新类,如下所示:

.select-generic-2.collapsing {
   z-index: 1;
   transition: z-index 0s 0s, max-height .25s ease-in-out 0s;
}

当另一个选择被打开时被调用,当另一个选择的扩展完成时被移除。

JS 看起来像这样:

   const select = document.querySelectorAll('.select-generic-2');
   //this is inside the event listener
   selected = this;
   select.forEach(function(el){
        if (el != selected){
            el.classList.remove("expanded");
            el.classList.add("collapsing");
        setTimeout(function(){
            el.classList.remove("collapsing");
        }, 250);}
    });

有点俗气的解决方案,但它有效!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多