javascript - 如何通过滚动动画 CSS 过渡效果?
问题描述
我有一个想要“扩展”并更改页面背景的背景颜色的元素。当用户滚动时,中心的一个点将扩展以用新的背景颜色填充页面。我看到了如何更改背景的示例,但没有看到如何“扩展”它。我附上了我正在寻找的 CSS 动画效果的 jsfiddle。此示例显示了它的外观,但仅适用于悬停。如果您滚动示例并将白点悬停,您可以看到它应该是什么样子。1
最好我想用 css 动画来完成这个,但我不反对用 javascript 来尝试它。我一直在这里摆弄。
其次,我一直在使用假元素来获取示例,但是有没有一种方法可以在不需要元素并且只使用容器的背景颜色的情况下实现这种效果?
这是我试图实现的效果示例的 HTML。
<div class="container">
<span class="white"></span>
</div>
这是CSS:
.container {height:500px;width:100%;background:#ed565d;position:relative;}
.container span {display:block;}
.white {background:#ffffff;height:10px;width:10px;margin:auto;border-radius:100%;position:absolute;top:50%;left:50%;}
.container:hover .white {
width:300%;
height:300%;
-moz-transition: all 0.5s ease-out;
-o-transition: all 0.5s ease-out;
-webkit-transition: all 0.5s ease-out;
transition:all 0.5s ease-out;
top:-100%;
left:-100%;
}
解决方案
如果您希望动画与用户在页面上滚动的百分比直接相关,则需要 JavaScript。
首先,获取滚动百分比。这是关于如何做到这一点的一个很好的答案:https ://stackoverflow.com/a/8028584/2957677
const scrollTop = $(window).scrollTop();
const documentHeight = $(document).height();
const windowHeight = $(window).height();
const scrollPercent = (scrollTop / (documentHeight - windowHeight)) * 100;
然后你可以定义一个动画函数,它接受用户滚动的百分比,并将圆圈上的样式设置为动画开始时的 CSS 值和动画结束时的 CSS 值之间的百分比.
function growAnimation($element, animationPercentage) {
const animationDecimal = animationPercentage / 100;
// Your existing .grow CSS values
const startPositionPercent = 50; // top/left at start of animation
const finishSizePercent = 300; // width/height at end of animation
const finishPositionPercent = -100; // top/left at end of animation
// The current CSS values, based on how far the user has scrolled
const currentSizePercent = getProgressFromTo(0, finishSizePercent, animationDecimal);
const currentPositionPercent = getProgressFromTo(startPositionPercent, finishPositionPercent, animationDecimal);
$element.css({
width: `${currentSizePercent}%`,
height: `${currentSizePercent}%`,
top: `${currentPositionPercent}%`,
left: `${currentPositionPercent}%`
});
}
// A util function to get the progress between two values
// e.g. 50% between 0 and 10 is 5
function getProgressFromTo(from, to, animationDecimal) {
return from + (to - from) * animationDecimal;
}
这是一个小提琴:https ://jsfiddle.net/owazk8y1
动画曲线
您可以查看动画曲线以使动画看起来更平滑。环绕animationDecimal
在贝塞尔曲线函数中。以下是一些示例函数:
https ://gist.github.com/gre/1650294
https://jsfiddle.net/owazk8y1/1
推荐阅读
- html - 将 margin-top 应用于 div 移动整个内容
- python - 如何根据keras中输入信号的SNR在训练期间为数据添加不同的噪声百分比?
- java - 使用Java在Android中启用switchbox时从edittext获取数据
- python - 你可以在windows中全局设置或删除python中的环境变量吗?
- flutter - Flutter 桌面应用程序 linux 上的 Gdk-CRITICAL 异常
- chisel - 如何创建 Chisel 模块的数组/vec
- python - 为什么 urlopen 不适用于某些网站?
- sql-server - 查找所有城市的计数
- html - 如何建立一个目录,链接到来自html的pdf中的书签?
- flutter - FLUTTER JUST_AUDIO Navigator.Push 播放完成后不起作用