我有一个元素,它的一个对 Angular 线边是通过调整线性渐变和高度实现的 - 在两种不同的状态下。现在我试着在这些状态之间切换,让红色三 Angular 形平滑过渡,这样它看起来就像一个跷跷板 :-) 问题是,从一个状态到另一个状态,它改变了方向并且是跳跃的,我没有找到一种让它流畅地动画化的方法..有没有办法使用纯 CSS 来实现我想要的东西,例如使用过渡?
let btn = document.getElementsByTagName('button')[0];
let stage = document.getElementById('stage');
btn.addEventListener('click', function() {
stage.classList.toggle('fixie');
});
body,
ul {
padding: 0;
margin: 0;
}
#stage {
width: 100%;
height: 14em;
background: pink;
padding: 0;
border: 1px solid blue;
}
#stage::before {
display: block;
position: relative;
width: 100%;
height: 100%;
/*as high as #stage*/
opacity: 0.4;
content: '';
z-index: 1;
background: linear-gradient(to left bottom, red 50%, pink 50%);
/*transition: height 4s;*/
/*transition: linear-gradient 4s 8s;*/
}
#stage.fixie::before {
height: 30%;
background: linear-gradient(to right bottom, red 50%, pink 50%);
}
<div id="stage"></div>
<button>animate gradient</button>
这是我的 FIDDLE
最佳答案
由于您无法为 linear-gradient
设置动画,因此这里有一个使用 transform
的解决方法
在此示例中,我使用了 skew
。由于倾斜程度会根据宽度/高度而有所不同,只要保持其比率,这将是完全响应式的,否则您将需要一个小脚本。
(function(){
let btn = document.getElementsByTagName('button')[0];
let stage = document.getElementById('stage');
btn.addEventListener('click', function() {
stage.classList.toggle('fixie');
});
})();
body, ul {
padding: 0;
margin: 0;
}
#stage {
position: relative;
overflow: hidden;
width: 90vw;
height: calc(90vw * 0.2677); /* 0.2677, aspect ratio that match skew degree */
background: pink;
padding: 0;
border: 1px solid blue;
}
.navi {
width: 100%;
min-height: 4em;
height: auto;
background: green;
z-index: 2;
position: relative;
}
#stage::before {
content: '';
position: absolute;
width: 100%;
height: 100%; /*as high as #stage*/
bottom: 100%;
opacity: 0.4;
z-index: 1;
background: red;
transform: skewY(15deg);
transform-origin: left bottom;
transition: transform 2s;
}
#stage.fixie::before {
transform: skewY(-15deg) translateY(100%);
}
.navi ul {
list-style: none;
display: flex;
background: lightblue;
justify-content: flex-end;
}
.navi ul li {
display: flex;
align-items: center;
justify-content: center;
min-width: 4em;
width: auto;
height: 2em;
margin: 1px;
background: yellow;
}
<div id="stage"></div>
<button>
animate
</button>
旁注:
只要保持 #stage
的比率,就可以使用任何固定值代替 vw
。如果要更改比率,您要么需要一个脚本,因为 CSS calc
无法使用 sqrt
和 sin
/ 进行数学运算cos
等获取 Angular ,或使用媒体查询,并为不同的屏幕手动设置 Angular 和比率。
关于javascript - 使用线性渐变(纯 CSS)实现动画跷跷板效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43803942/