【问题标题】:Possible to animate grid-area property?可以为网格区域属性设置动画吗?
【发布时间】:2019-08-16 17:13:52
【问题描述】:
我有一个用于 2 个按钮的覆盖元素,我试图通过更改元素的 grid-area 属性以匹配已单击按钮的属性来实现一种活动状态。
我想知道是否可以为这种变化制作动画并制作某种幻灯片动画。
const overlay = document.querySelector('.overlay');
const hello = document.querySelector('.btn-1');
const world = document.querySelector('.btn-2');
hello.addEventListener('click', e => {
overlay.style.gridArea = '1 / 1 / -1 / 2';
});
world.addEventListener('click', e => {
overlay.style.gridArea = '1 / 2 / -1 / -1';
});
.grid {
width: 1000px;
display: grid;
grid-template: 1fr / repeat(2, min-content);
}
.overlay {
background-color: cornflowerblue;
width: 100%;
height: 100%;
grid-area: 1 / 1 / -1 / 2;
}
.btn {
text-align: center;
width: 100px;
font-size: 30px;
font-family: sans-serif;
padding: 20px 40px;
cursor: pointer;
}
.btn-1 {
grid-area: 1 / 1 / -1 / 2;
}
.btn-2 {
grid-area: 1 / 2 / 2 / -1;
}
<div class="grid">
<div class="overlay"></div>
<span class="btn btn-1">Hello</span>
<span class="btn btn-2">World</span>
</div>
【问题讨论】:
标签:
javascript
css
css-transitions
css-grid
dom-events
【解决方案1】:
好的,我找到了一个很好的库,可以很容易地完成这个任务。由于某种原因,我无法在 sn-p 中包含 cdn 链接,但该项目在 github 上称为 animate-css-grid。
const overlay = document.querySelector('.overlay');
const hello = document.querySelector('.btn-1');
const world = document.querySelector('.btn-2');
const grid = document.querySelector('.grid');
animateCSSGrid.wrapGrid(grid, {duration : 600});
hello.addEventListener('click', e => {
if (overlay.classList.contains('overlay--2')) {
overlay.classList.remove('overlay--2');
}
});
world.addEventListener('click', e => {
if (!overlay.classList.contains('overlay--2')) {
overlay.classList.add('overlay--2');
}
});
.grid {
width: 1000px;
margin: 100px auto;
display: grid;
grid-template: 1fr / repeat(2, min-content);
}
.overlay {
background-color: cornflowerblue;
width: 100%;
height: 100%;
grid-area: 1 / 1 / -1 / 2;
z-index: -1;
}
.overlay--2 {
grid-area: 1 / 2 / -1 / -1;
}
.btn {
text-align: center;
width: 100px;
font-size: 30px;
font-family: sans-serif;
padding: 20px 40px;
cursor: pointer;
}
.btn-1 {
grid-area: 1 / 1 / -1 / 2;
}
.btn-2 {
grid-area: 1 / 2 / 2 / -1;
}
<div class="grid">
<div class="overlay"></div>
<span class="btn btn-1">Hello</span>
<span class="btn btn-2">World</span>
</div>