简体   繁体   中英

iOS 8 Page Jumping on Input Focus

On iOS 8's Safari, when I focus on an <input> element, the entire page jumps down suddenly, before returning to its original position. My page layout fills the entire screen and is not intended to be scrolled.

This seems to be the same bug observed here and here , and in this video . The solutions in those situations were for Cordova apps, but I am not building a Cordova app, I am just making a website for Mobile Safari.

I've tried adding html, body { position: fixed; } html, body { position: fixed; } as suggested here , but that didn't work.

I would try to "disable scrolling" with the ontouchmove suggestion that many people have provided before, but this is not scrolling triggered by the user, it is automatic scrolling.

I've tried adding onfocus="window.scrollTo(0, 0);" as suggested here , but that didn't work, and I wouldn't expect it to given the comment on that answer:

This seems like it should work, but it's not working for me on an iPhone 5S with iOS 8 in Safari. event.preventDefault() in combination with your solution seems like it would definitely work, but I still get the default scrolling behavior. – benny Mar 17 at 17:53

How do I prevent this bounce?

Try this, in my case worked:

$(document)
    .on('focus', 'input', function(e) {
        $('body').addClass('fixfixed');
    })
    .on('blur', 'input', function(e) {
        $('body').removeClass('fixfixed');
    });
}

In my case I transform all the fixed element on the web on absolute to fix the problem in iOS when I do a focus on input:

$(document)
    .on('focus', 'input', function(e) {
        $('body').addClass('fixfixed');
        $('*').filter(function() {
            return $(this).css("position") === 'fixed';
        }).addClass('fixfixed');
    })
    .on('blur', 'input', function(e) {
        $('body').removeClass('fixfixed');
        $('*').filter(function() {
            return $(this).css("position") === 'fixed';
        }).removeClass('fixfixed');
    });
}

The class fixfixed have a position: absolute !important;

I think the first solution for your case it should work

I discovered the issue was caused by a piece of code we had which was setting the scrollTop of the page to 0 on focus. No wonder!

document.addEventListener('focusin', function (event) {
    if (event.target.tagName === 'INPUT') {
        document.body.scrollTop = 0;
    }
});

Simply remove the bottom script and the problem goes away.

If you are focusing the element programmatically, this worked for me:

setTimeout(() => {
  element.focus();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM