javascript - Target 的切换 ClassList 上的 CSS 转换不起作用
问题描述
我希望高度平滑扩展,但 95% 的时间不会发生过渡。这是因为 classList.toggle 创建了一个新的类字符串,因此转换丢失了吗?无论哪种方式,我该如何解决这个问题?我必须为此使用香草 JS。
document.querySelectorAll('.toggleMe').forEach(function (query) {
query.onclick = function (e) {
e.target.classList.toggle('open');
}
});
.toggleMe {
background: #e3e3e3;
max-height: 1.3rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 100%;
transition: all ease 2s;
-moz-transition: all ease 2s; /* Firefox 4 */
-webkit-transition: all ease 2s; /* Safari and Chrome */
-o-transition: all ease 2s; /* Opera */
-ms-transition: all ease 2s; /* Explorer 10 */
}
.toggleMe.open {
max-height: 999px;
white-space: normal;
}
<div class="toggleMe">I am a really long sentence that wants to stay hidden on load, but when clicked will expand for all to see. But 95% of the time, the transition doesn't happen. Is this because the classList.toggle creates a new class string, and therefore the transition is lost?</div>
解决方案
将设置想象max-height
成一种以动画方式垂直打开和关闭的窗口/视口。
同时,该white-space
设置使段落的高度立即增加或减少,没有动画。
当段落的高度立即增加时,只有在窗口开始时处于完全关闭位置时才能看到动画,因为当窗口开始打开时,它会显示段落。
折叠时,段落会立即折叠,但max-height
窗口关闭需要整整 2 秒。这并不明显,因为所有这些时间都花在了几乎999px
所有想象中的房地产上。
因此,您必须等待整整 2 秒才能关闭该窗口,以便下次看到展开动画。否则,如果您不等待,窗口仍然是部分打开的,并且它开始再次打开而没有首先稳定到其最小高度。因此,它无法重新创建动画。
我认为它似乎间歇性失败的原因是,在您的测试期间,您在展开、折叠和重新展开之间等待了不同的时间。
我希望这是有道理的。在高度不可预测的文本上创建展开/折叠效果肯定有点棘手。如果您减少max-height: 999px
设置,它可以最大限度地减少问题。但它可能会切断更大的段落:/
推荐阅读
- php - RewriteRule - 丢弃尾部斜杠
- r - 传递给函数的顺序数据帧
- arrays - 带有数组的 SAS Find()
- javascript - 如何在 Angular 中预填充 ngselect?
- javascript - 调用 onBlur 时,Firefox 中的relatedTarget 为空
- python - 将 sql 表放入 python 错误。怎么了?
- javascript - 没有参数的异步递归函数会泄漏内存或堆栈溢出吗?
- azure - Azure Databricks 群集 API 身份验证
- azure - Application Insights 警报。通过 ARM 模板设置抑制时间
- php - 如何使用 wp_get_theme 修改 singlepost.php