我正在寻找一种在用户滚动页面时为某些元素设置动画(使用 @keyframes
、transform
...)的方法。例如:
- 当偏移量为 0 时:
div
有height: 100px
。 - 当偏移量在 0 到 100 之间时:
div
为height: 50px
和color: blue
。 - 等等...
是否可以使用纯 CSS? 如果不是,使用 HTML 或 Javascript 最有效的方法是什么?
最佳答案
根据滚动位置为元素的样式属性设置动画的最有效方法可能是添加一个具有滚动功能的类:
myID = document.getElementById("myID");
var myScrollFunc = function() {
var y = window.scrollY;
if (y > 500) {
// myID.style.backgroundColor = "blue"; // you can add individual styles
myID.className = "blue" // or add classes
} else {
// myID.style.backgroundColor = "red";
myID.className = "red"
}
};
window.addEventListener("scroll", myScrollFunc);
body {
height: 1100px;
}
#myID {
position: fixed;
height: 100px;
line-height: 20px;
transition: all 1s;
}
.blue {
background: blue;
animation: myAnimation 1s both;
}
.red {
background: red;
}
@keyframes myAnimation {
0% {
border-radius: 0px;
line-height: 10px;
}
100% {
border-radius: 100%;
line-height: 100px;
}
}
<div id="myID" class="red">Hello world</div>
文档:
关于html - 滚动页面时如何为纯 CSS 中的部分设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32208560/