使用纯 Javascript 滚动动画 WKWebView

Scroll with animation a WKWebView using pure Javascript

我使用以下代码,它应该在给定动画持续时间的给定偏移处滚动 webview。但它不起作用。我对 Javascript

不是很有经验
- (NSString *)jsCodeScrollTo:(NSInteger)offset withAnimationDuration:(NSInteger)animationDuration
{
    return [NSString stringWithFormat:@" scrollTo(document.documentElement, %ld, %ld); function scrollTo(element, to, duration) { if (duration < 0) return; var difference = to - element.scrollTop; var perTick = difference / duration * 10; setTimeout(function() { element.scrollTop = element.scrollTop + perTick; if (element.scrollTop === to) return; scrollTo(element, to, duration - 10); }, 10); }", offset, animationDuration];
}

它输出:

scrollTo(document.documentElement, 2841, 2000); 
    function scrollTo(element, to, duration) { if (duration < 0) return; 
    var difference = to - element.scrollTop; 
    var perTick = difference / duration * 10; 
    setTimeout(function() { element.scrollTop = element.scrollTop + perTick; 
    if (element.scrollTop === to) return; 
    scrollTo(element, to, duration - 10); }, 10); }

我使用了此线程中发布的代码:Cross browser JavaScript (not jQuery...) scroll to top animation

这里是不是JS代码有问题?或者在 WebKit 中 运行 时出现问题(兼容性问题)?

解决方法是,先插入JS函数定义再调用。

- (void)scrollTo:(NSInteger)offset withAnimationDuration:(NSInteger)animationDuration {
    [self insertJavascriptAnimationFunction];
    [webView evaluateJavaScript:[NSString stringWithFormat:@"scrollTo(document.body, %ld, %ld);", offset, animationDuration]
              completionHandler:nil];
}

- (void)insertJavascriptAnimationFunction
{
    [webView evaluateJavaScript:@"function scrollTo(element, to, duration) { var start = element.scrollTop, change = to - start, currentTime = 0, increment = 20; var animateScroll = function(){ currentTime += increment; var val = Math.easeInOutQuad(currentTime, start, change, duration); element.scrollTop = val; if(currentTime < duration) { setTimeout(animateScroll, increment); } }; animateScroll(); } Math.easeInOutQuad = function (t, b, c, d) { t /= d/2; if (t < 1) return c/2*t*t + b; t--; return -c/2 * (t*(t-2) - 1) + b; };"
              completionHandler:nil];
}