一聚教程网:一个值得你收藏的教程网站

热门教程

CSS3 Animations创建返回顶部的平滑动画

时间:2022-11-14 23:38:46 编辑:袖梨 来源:一聚教程网

一般在一个长的网页中,我们都会有一个按钮,让用户能够快速的定位到网页的不同地方,一般都是一个返回顶部的按钮,这个功能我们都是使用的jQuery来完成,但是今天,我们为大家讲解一下不使用jQuery而是使用CSS3的动画,创建返回顶部的平滑动画效果。

返回顶部的动画效果,能够让我们快速的导航到菜单栏,通常,我们使用jQuery代码是这么编写代码的

$( 'body, html' ).animate({ scrollTop : 0 }, 800 );

所以,如果我们设置scrollTop为500,那么网页将滚动到离顶部还有500px的位置上面。

CSS3给我们带来了很多高级的功能,比如说动画效果,我就在想一种不依赖JavaScript的解决方法,最后我发现这是不可能实现的,因为我们仅仅通过CSS代码是无法访问CSS3 Animations API。

我有点不甘心,就这样的放弃,我决定试试通过JavaScript获取到CSS3动画的API,于是我找到了一个方法。

想法很简单,首先我们需要使用jQuery API获取到当前滚动的距离定义为:POS,然后在我们的元素中设置margin-top负的:-POS属性,所以现在我们有了一个初步的方法,我们可以看到,当滚动距离的增加,和滚动滑条的随机位置如下图表示:

让我们继续滚动到0的位置,这使微积分更精确,最后触发滚动动画前我们只有启动transition在body元素中,并改变margin为0,这让我们一到顶部的平滑效果看整个网站的幻灯片,和滚动手柄上始终保持0的位置,并通过与宽松的功能打一点,我们可以看到一个惊人的效果,你可以看到上面的示范。

实现方法

让我们说,我们有这个按钮:

Go to Top

现在让我们搬到jQuery的一部分:

// Define the variables var easing, e, pos;
$( function (){
// Get the click event
$( "#go-top" ).on( "click" , function (){
// Get the scroll pos
pos= $(window).scrollTop();
// Set the body top margin
$( "body" ).css({ "margin-top" : -pos+ "px" , "overflow-y" : "scroll"});
// This property is posed for fix the blink of the window width change
// Make the scroll handle on the position 0
$(window).scrollTop( 0 );
// Add the transition property to the body element
$( "body" ).css( "transition" , "all 1s ease" );
// Apply the scroll effects
$( "body" ).css( "margin-top" , "0" );
// Wait until the transition end $( "body" ).on( "webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd" , function (){
// Remove the transition property
$( "body" ).css( "transition" , "none" );
});
});
});

现在,如果你点击 div#go-top 按钮,将使用CSS3过度动画跳转到网页的顶部。

如何使用easing
不得不说,在CSS中的动画中,easing使用的太有极限性了,不够灵活。

结论

对我来说,我觉得这个方法很好的解决方案来代替传统的jQuery的使用它,它也将滚动手柄的高度如果你注意到

热门栏目