在不添加/删除CSS类的情况下,将元素插入到flexbox时进行CSS转换



假设我无法访问JavaScript,只能编辑CSS。

我仍然应该能够定义一个转换,这样当JS(我不控制(将一个新元素插入到flex容器中时,容器就会平滑地变宽,对吧?

// 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更改(如何实现目标

在过去的几年里,类似的问题(例如是否可以动画化flexbox插入、删除和项目位置?(已经收集了关于如何定义CSS转换的答案,但它们都需要JavaScript来添加或删除元素的类名。

澄清一下:我不希望JavaScript操纵任何现有元素的classList。唯一允许的JavaScript是将新的元素实际插入到flexbox容器中,例如在我的示例中。

第页。另外,我需要新元素在它自己的行上,这就是我使用flex-wrap: wrap;的原因。

您可以执行以下插入操作。我怀疑您是否有幸删除,因为CSS之前无法删除事件。

// 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;
}
.old {
background: #ccc;
border: 1px solid black;
}
#new {
flex: 1 1 0;
border: 1px solid red;
animation:grow 1s forwards;

height:0;
flex-basis:0;
min-width:0;
overflow:hidden;
}
@keyframes grow {
to {
height:120px;
flex-basis:100%;
}
}
<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>

最新更新