如何使用FB.Canvas.scrollTo实现动画效果?

13

我创建了一个应用程序,其大小固定(大约为2,000像素高),并有一个菜单调用FB.Canvas.scrollTo以帮助用户浏览长页面。

是否有任何方法添加平滑滚动效果?Facebook在其开发者博客上没有提供任何解决方案。

4个回答

47

使用 @Jonny 的方法,您可以更简单地完成此操作。

function scrollTo(y){
    FB.Canvas.getPageInfo(function(pageInfo){
            $({y: pageInfo.scrollTop}).animate(
                {y: y},
                {duration: 1000, step: function(offset){
                    FB.Canvas.scrollTo(0, offset);
                }
            });
    });
}

$ 最有可能是 jQuery。使用 $('#button_id').click(function() { FB.Canvas.scrollTo(0,0); }); - Milan Babuškov
1
在使用“y”作为函数参数和jQuery的“animate”内置参数时可能会有点混淆,但它确实可以工作。万岁! - Brade

5

今天我遇到了同样的问题 - 我写了一小段JavaScript代码,利用了jQuery的animate方法,它提供了一些缓动效果 - 滚动仍然有些卡顿(我猜这是由于FB.Canvas.scrollTo代理引起的)。无论如何,以下是代码片段:

function scrollToTop() {
    // We must call getPageInfo() async otherwise we will get stale data.
    FB.Canvas.getPageInfo(function (pageInfo) { 

        // The scroll position of your app's iFrame.
        var iFrameScrollY = pageInfo.scrollTop;

        // The y position of the div you want to scroll up to.
        var targetDivY = $('#targetDiv').position().top;

        // Only scroll if the user has scrolled the window beneath the target y position.
        if (iFrameScrollY > targetDivY) {
            var animOptions = {

                // This function will be invoked each 'tick' of the animation.
                step: function () {
                    // As we don't have control over the Facebook iFrame we have to ask the Facebook JS API to 
                    // perform the scroll for us.
                    FB.Canvas.scrollTo(0, this.y);
                },

                // How long you want the animation to last in ms.
                duration: 200
            };

            // Here we are going to animate the 'y' property of the object from the 'iFrameScrollY' (the current 
            // scroll position) to the y position of your target div.
            $({ y: iFrameScrollY }).animate({ y: targetDivY }, animOptions);
        }
    });
}

2
我刚刚使用了Francis的技巧,并实现了一个jQuery版本。
$('html,body').animate(
  {scrollTop: $(".scroll_to_me").offset().top}, 
  {duration: 1000, step: function(top_offset){
    FB.Canvas.scrollTo(0, top_offset + 30);
  }
});

您需要将.scroll_to_me替换为您想要滚动到的选择器。另外,我在偏移量中添加了+ 30,因为iframe不是从页面顶部开始的,您可能需要进行微调。


嗯,当我实现它时,它会跳到页面顶部,然后滚动。在我的情况下,当用户点击按钮时,他们不总是在页面顶部,因此在平滑滚动之前进行跳跃并不完全适用。 - Carson

0
一种实现方法是获取当前 Y 位置,然后获取目标 Y 位置。使用 setTimeout 运行一个 for 循环,将用户带到最终的 Y 位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接