jQuery scrollTop在iOS的iframe中不起作用

Dir*_*irk 6 iframe jquery scrolltop ios

iOS和iframe ..这样的痛苦。我有一个简单的“ 返回页首”按钮,该按钮应使滚动具有动画效果(而不仅仅是跳转到页面顶部)。

$(document).on('click touchstart', '.backtotop', function() {
    $('html, body').animate({ scrollTop: 0 }, 1500);
});
Run Code Online (Sandbox Code Playgroud)

除iOS上的iframe外,此功能均可在所有地方使用。我仍然不太了解iOS如何处理iframe。jQuery的.scrollTop()函数也不起作用(无论如何都不能动画)。

在iOS上的iframe中唯一起作用的是:

parent.self.scrollTo(0, 0);
Run Code Online (Sandbox Code Playgroud)

显然,这不是最佳解决方案,因为它不适用于桌面浏览器。通常,如果您对如何在iOS上修复此问题或iframe有了更深入的了解,将非常感谢。

Dir*_*irk 5

似乎特定于上下文可以解决此问题:

$('body, html', parent.document).animate({ scrollTop: 0 },1500);
Run Code Online (Sandbox Code Playgroud)

由于这仅适用于iOS,因此我在该线程中包含了iOS检测:

var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false );

$(document).on('click touchstart', '.backtotop', function() {
    if (iOS) {
        $('html, body', parent.document).animate({ scrollTop: $("body").offset().top},1500,"easeOutQuart");
    } else {
        $('html, body').animate({ scrollTop: $("body").offset().top},1500,"easeOutQuart");
    }
});
Run Code Online (Sandbox Code Playgroud)

显然,只有parent.document作为上下文。parent.window或仅文档无效。

  • 很好的解决方案!`parent.document`帮了我大忙。谢谢 (2认同)