有没有一种使用CSS3实现滚动动画的方法?
像这样的效果?
@-webkit-keyframes scrolltoview
{
0% { scrollTop: 0; }
100% { scrollTop: 30%; }
}
如何在CSS中指定动画的起始点?
有没有一种使用CSS3实现滚动动画的方法?
像这样的效果?
@-webkit-keyframes scrolltoview
{
0% { scrollTop: 0; }
100% { scrollTop: 30%; }
}
如何在CSS中指定动画的起始点?
如此处所解释的那样,您可以使用margin-top
技巧并动态更新滚动位置来实现这一点。您可以查看演示。代码很简单:
// 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");
});
});
});
@AndrewP 提供了一个基于这个想法的不错的工作示例
documentElement
上使用scrollTop
,但在Safari中失败了,尽管它应该是标准方法。最终通过https://dev59.com/k2435IYBdhLWcg3whQY5#YqSeEYcBWogLw_1bWgYG找到了一个在Safari、Chrome、Firefox甚至IE 8(http://cdpn.io/bFBDr)中都有效的解决方案。 - Andrew PattonCSS3动画只与CSS属性一起工作。这在CSS的限制范围内是不可能的。
function whichTransitionEvent() {
var t,
el = document.createElement('fakeelement'),
transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
};
for (t in transitions){
if (el.style[t] !== undefined){
return transitions[t];
}
}
}
function backToTop() {
var pos_from_top = window.scrollY,
transitionend = whichTransitionEvent(),
body = document.querySelector("body");
function scrollEndHandler() {
window.scrollTo(0, 0);
body.removeAttribute("style");
body.removeEventListener(transitionend, scrollEndHandler);
}
body.style.overflowY = "scroll";
window.scrollTop = 0;
body.style.webkitTransition = 'all .5s ease';
body.style.transition = 'all .5s ease';
body.style.webkitTransform = "translateY(" + pos_from_top + "px)";
body.style.transform = "translateY(" + pos_from_top + "px)";
transitionend && body.addEventListener(transitionend, scrollEndHandler);
}
这是我制作的一个非常简单的 .js 函数,用于动画和滚动网页。
var Current_scroll_Y=0;
var Target_scroll_Y=0;
var scroll_Speed = 15;
function animate_Scroll(Y)
{
Target_scroll_Y = Y;
screen_Y = Math.floor(window.scrollY);
//Scroll Down
if(screen_Y<Y)
{
var myWindowScroll = setInterval(function(){ screen_Y = screen_Y+scroll_Speed; if(screen_Y>=Target_scroll_Y){ clearInterval(myWindowScroll); return;} window.scrollTo(0, screen_Y); }, 3);
}
//Scroll Up
if(screen_Y>Y)
{
var myWindowScroll = setInterval(function(){ screen_Y = screen_Y-scroll_Speed; if(screen_Y<=Target_scroll_Y){ clearInterval(myWindowScroll); return;} window.scrollTo(0, screen_Y); }, 3);
}
}//End animate_Scroll