首页 > 解决方案 > 如何通过滚动动画 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%;
}

标签: javascriptcssanimationcss-animations

解决方案


如果您希望动画与用户在页面上滚动的百分比直接相关,则需要 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


推荐阅读