javascript - FadeIn/FadeOut 使 DIV 的堆栈而不是重叠?使用 'absolute' 不是解决方案

标签 javascript jquery

我目前正在使用以下代码来淡入/淡出各种 DIV(其中包含信息)。这有效,但我对结果不满意。它应该相互重叠,而不是相互堆积。

我进行了搜索,唯一可行的方法是添加:position:absolute;在 CSS 中。虽然这有效,但它会弄乱它下面的其余项目。所以我想解决这个问题。

我确实读过有关插入所谓的回调函数的信息,但是我不知道如何将其用于此编码。

这是一段淡入/淡出代码:

$('.extraInfo').hide();

$('input').on('ifChecked', function(event){
    var extraInformationId = $(this).closest('label')[0].id;
    if(extraInformationId != undefined) {
        $('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeIn(500);
    }
});

$('input').on('ifUnchecked', function(event){
    var extraInformationId = $(this).closest('label')[0].id;
    if(extraInformationId != undefined) {
        $('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeOut(500);
    }
});

除了将 CSS 更改为绝对值之外,我自己能想到的最好的方法是将淡入/淡出从 500 更改为 0。但这并不是真正的解决方案。 :|

如果您需要更多信息和/或详细信息,这里是 JSFiddle .

当您单击项目时,您会注意到 DIV 正在堆叠。在我看来,这让事情看起来有点“丑陋”。

最佳答案

删除 ifUnchecked 部分并将其用于 ifChecked

$('input').on('ifChecked', function(event){
    $("div.extraInfo")
        .fadeOut(500)    // hide all divs with class `extraInfo`
        .promise()       // "wait" for the asynchonous animations to complete
        .done(function() {    // and then show the info for the selected one
            var extraInformationId = $(this).closest('label').attr("id");

            if(extraInformationId) {
                $('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeIn(500);
            }
        }.bind(this));    // preserve the value of this for the callback of fadeOut
});

fiddle

关于javascript - FadeIn/FadeOut 使 DIV 的堆栈而不是重叠?使用 'absolute' 不是解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040018/

相关文章:

javascript - 如何让导航栏淡入后淡出到顶部?

javascript - 区分用户启动的滚动和页面加载时发生的浏览器启动的滚动

javascript - 按下按钮时制作全高和全宽的菜单栏

javascript 表格技巧隐藏和显示点击按钮的除法

javascript - 钛javascript事件

JavaScript 循环创建innerHTML(Google Sheet)

javascript - d3 地理动画不会停止

javascript - 为什么 anchor 不能仅在 Firefox 中使用 map 坐标?

javascript - onclick 属性与 eventListeners

javascript - 使用高整数数组索引有什么负面影响吗?