有没有办法用CSS3动画滚动?
这样的东西?
@-webkit-keyframes scrolltoview
{
0% { scrollTop: 0; }
100% { scrollTop: 30%; }
}
如何将css放入动画的起始点?
答案 0 :(得分:15)
正如here所述,您可以使用margin-top
技巧并动态更新滚动位置。您可以查看demo。代码很简单:
// 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根据这个想法提供了一个不错的working example
答案 1 :(得分:9)
css3动画仅适用于css属性。这在css的范围内是不可能的。
答案 2 :(得分:4)
我发现了一种更好的滚动动画方法,即使用JavaScript来翻译文档正文。平移边距或位置的动画效果非常well documented。最重要的是,当动画元素时,GPU总能做得更好。
这是一个从窗口顶部计算用户当前位置然后平滑地转换回窗口顶部的示例。假设用户点击或触摸事件触发了backToTop功能。
查看实际操作:https://antibland.github.io/starting_point/
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);
}
答案 3 :(得分:1)
这是一个非常简单的.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
答案 4 :(得分:0)