【问题标题】:Scroll with animation a WKWebView using pure Javascript使用纯 Javascript 滚动动画 WKWebView
【发布时间】:2015-12-29 20:09:59
【问题描述】:

我使用下面的代码,它应该在给定的偏移量处以给定的动画持续时间滚动 web 视图。但它不起作用。我对 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 中运行时出现问题(兼容性问题)?

【问题讨论】:

    标签: javascript ios objective-c ios9 wkwebview


    【解决方案1】:

    解决方法是,先插入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];
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2015-03-14
      相关资源
      最近更新 更多