gpt4 book ai didi

javascript - 如何切换显示 :none/display:block whilst first animating/transitioning

转载 作者:行者123 更新时间:2023-11-28 01:00:44 27 4
gpt4 key购买 nike

这里以各种复杂的形式提出了类似的问题。一些使用 jQuery:

How to toggle animate with css display:none .

还有一些非常具体的内容忽略了要实现的目标的范围和简单性:

JavaScript - add transition between display:none and display:block .

但以这段非常精简的代码为例:

var button = document.getElementsByTagName( 'button' )[ 0 ],
div = document.getElementsByTagName( 'div' )[ 0 ];

button.addEventListener( 'click', toggleVisibility );

function toggleVisibility(){
if(
div.classList.contains( 'show' )
){
div.classList.remove( 'show' );
div.classList.add( 'hide' );
}
else {
div.classList.add( 'show' );
div.classList.remove( 'hide' );
}
}
div {
height: 100px;
width: 100px;
background: #000;
transition: 1s;
}

.hide {
opacity: 0;
}

.show {
opacity: 1;
}
<p>A square</p>

<div class="show"></div>

<br>

<button>click to toggle hide/show</button>

这成功地切换了不透明度。但是一旦我将 display: none 添加到 .hide 类中,效果就会非常糟糕:

var button = document.getElementsByTagName( 'button' )[ 0 ],
div = document.getElementsByTagName( 'div' )[ 0 ];

button.addEventListener( 'click', toggleVisibility );

function toggleVisibility(){
if(
div.classList.contains( 'show' )
){
div.classList.remove( 'show' );
div.classList.add( 'hide' );
}
else {
div.classList.add( 'show' );
div.classList.remove( 'hide' );
}
}
div {
height: 100px;
width: 100px;
background: #000;
transition: 1s;
}

.hide {
display: none; /* added "display:none" in this example */
opacity: 0;
}

.show {
opacity: 1;
}
<p>A square</p>

<div class="show"></div>

<br>

<button>click to toggle hide/show</button>

有什么简单的、可重复使用的解决方案,我们可以在没有任何插件或库的情况下使用,先淡出,然后关闭 display,然后先打开 display,然后淡入?

编辑: 我在 visibility 上使用 display 因为在这个例子中,在大多数情况下我使用这个效果我想完全删除元素因为它通常位于阻碍 mouseover/click 效果的其他元素之上。

最佳答案

pointer-events 添加到您的 .hide 类应该可以解决问题。

.hide {
pointer-events: none;
opacity: 0;
}

关于javascript - 如何切换显示 :none/display:block whilst first animating/transitioning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42264609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com