【发布时间】:2021-07-15 00:40:27
【问题描述】:
假设我无法访问 JavaScript,只能编辑 CSS。
我仍然应该能够定义一个过渡,这样当 JS(我无法控制)将一个新元素插入到弹性容器中时,容器会平滑变宽,对吗?
// For the purposes this demo (to make it useful for my actual challenge),
// the only "allowed" JS is JS that adds or deletes an item within the container.
function insertOrDeleteExtraElement() {
const div = document.getElementById("new");
if (div) {
div.parentNode.removeChild(div);
} else {
const newDiv = document.createElement('div');
newDiv.innerHTML = "Inserting or deleting this should transition the container's width smoothly, honoring the transition duration.";
newDiv.id = "new";
document.getElementById("container").appendChild(newDiv);
}
}
#container {
border: 2px dashed blue;
display: inline-flex;
flex-wrap: wrap;
max-width: 250px;
transition: all 1s;
}
input {
flex: 1 1 100px;
transition: all 1s;
}
#new {
flex: 1 1 100%;
display: block;
border: 1px solid red;
height: 120px;
transition: all 1s;
}
.old {
background: #ccc;
border: 1px solid black;
}
<button onclick="insertOrDeleteExtraElement();" style="font-size: 16px;">Click here</button>
<br/>
<div id="container">
<input type="text" value="old input" class="old"/>
<div class="old">old div</div>
</div>
如何仅使用 CSS(不更改 JavaScript 或 HTML)来实现我的目标?
过去几年的类似问题(例如Is it possible to animate flexbox inserts, removes, and item position?)收集了有关如何定义 CSS 过渡的答案,但它们都需要 JavaScript 来添加或删除元素的类名。
澄清一下:我不希望 JavaScript 操作任何现有元素的 classList。唯一允许的 JavaScript 是将 new 元素实际插入到 flexbox 容器中,例如在我的示例中。
附:此外,我需要将新元素放在自己的行上,这就是我使用flex-wrap: wrap; 的原因。
【问题讨论】:
-
可以插入但不能删除