jQuery scrollTop not working inside iframe on iOS

百般思念 提交于 2019-11-28 04:10:19

问题


iOS and iframes.. such a pain. I've a simple back to top button which should animate the scrolling (instead of just jumping to the top of the page).

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

This works everywhere, except for iframes on iOS. I still haven't fully understood how iOS handles iframes. jQuery's .scrollTop() function won't work either (which can't be animated anyway).

The only thing which works in iframes on iOS is this:

parent.self.scrollTo(0, 0);

Obviously not the best solution since this won't work for desktop browsers. Any deeper knowledge on how to fix this or iframes on iOS in general is greatly appreciated.


回答1:


Seems like specificing the context fixes the issue:

$('body, html', parent.document).animate({ scrollTop: 0 },1500);

Since this will only work for iOS I've included the iOS detect from this thread:

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");
    }
});

Apparently only parent.document works as the context. parent.window or only document have no effect.



来源:https://stackoverflow.com/questions/30478157/jquery-scrolltop-not-working-inside-iframe-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!