gpt4 book ai didi

javascript - 替换两个 div 时底部内容不会闪烁

转载 作者:太空宇宙 更新时间:2023-11-04 07:41:06 24 4
gpt4 key购买 nike

我有两个内容非常相似的 div。单击按钮时,我希望第一个 div 消失,第二个出现在完全相同的位置。它们没有恒定的高度,但它们应该具有相同的自动高度,因为它们具有非常相似的内容。

我实现了这个例子来演示这个问题。在此代码段中,您可以看到单击按钮后,div 将替换为淡入/淡出动画。问题是下面的内容(本例中的 text text)在淡入/淡出过程中上下移动,这对用户体验产生了负面影响。

假设这些div下面有很多内容,那看起来就不太好。

在替换期间不让 div 下面的所有内容“闪烁”的情况下实现此行为的最佳方法是什么?

$("#clicker").click(function() {
if ($('.first').is(':visible')) {
$('.first').fadeOut();
$('.second').fadeIn();
} else {
$('.second').fadeOut();
$('.first').fadeIn();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<button id="clicker">Click me</button>

<div style="background-color:yellow;display:none" class="first">first content</div>
<div style="background-color:red" class="second">second content</div>

<div id="more_stuff_here">
text text<br> text text
</div>

最佳答案

发生这种情况是因为您为 display:nonedisplay:block 应用了 fade 效果。所以它会扰乱你的布局,因为在动画的某个点,两个元素都变成了 display:block

所以解决方案是在执行display:none 时不需要淡入淡出效果。只需使用 hide()

所以用hide()代替fadeOut()fadeIn() 将为您的内容添加动画效果。

堆栈片段

$("#clicker").click(function() {
if ($('.first').is(':visible')) {
$('.first').hide();
$('.second').fadeIn();
} else {
$('.second').hide();
$('.first').fadeIn();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<button id="clicker">Click me</button>
<div style="background-color:yellow;display:none" class="first">first content</div>
<div style="background-color:red" class="second">second content</div>
<div id="more_stuff_here">
text text<br> text text
</div>

关于javascript - 替换两个 div 时底部内容不会闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48509088/

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