scrollTo() with ipad and fixed element [duplicate]

2020-06-28 16:51发布

问题:

This question already has answers here:
Closed 8 years ago.

Possible Duplicate:
Mobile Safari bug on fixed positioned button after scrollTop programmatically changed…?

We're trying to put a fixed navigation to scroll the different sections of a page.

We're using jquery scrollTo().

Only on ipad, the first click pass without problem, but after this one, the on the navigation seems to be disabled. If we scroll, even a little bit, with the hand, then the link's work again.

Here is the code : http://lacabaneprod.com/test/

How can I fix my sidebar ?

回答1:

Ran into the same issue a few weeks ago.

The reason this happens is because the "content" gets the focus, and tapping the screen "taps" the content behind the sidebar. This only happens if you use the scrollTo plugin, or jquery.animate on the scrollTop property.

To fix this, after the scrollTo animation, we repositioned the window.

$(window).scrollTop($(window).scrollTop() + 1);    
$(window).scrollTop($(window).scrollTop() - 1);

But also keep in mind that fixed positions are not supported prior to iOS 5.



回答2:

For anyone who is experiencing this problem using Ariel Flesler's LocalScroll plugin, Arief's answer above works and can be applied in the following way:

$(document).ready(function() {
$.localScroll.defaults.axis = 'x';
$.localScroll({
    target:'#content',
    onAfter:function(){
        var xPos = window.pageXOffset;
        var $fixedElement = $('#menubar');
        $fixedElement.css({ "position": "absolute" });
        window.scroll(xPos,0);
        $fixedElement.css({ "position": "fixed" });
        }
    });

});

In this case, I have a horizontally scrolling website (hence defaulting to the 'x' axis - yours may be different). I am scrolling a '#content' div which is set to 'overflow:hidden' (hence the 'target'). And then all of Arief's magic is in the 'onAfter:function'.

I have tweaked this so that instead of 'window.scroll(0,0)' - which scrolls back to the very beginning of the page - it gets the current window scroll position by using the window.pageXOffset and sets a variable "xPos" for this (again, if you are scrolling on the Y axis, or even both, you may need to use window.pageYOffset also). This variable is then used in the 'window.scroll(xPos,0)' - mine is "0" on the y axis, as am not scrolling on that axis. I believe there may be different ways of calculating current scroll position, but this worked best for me.

I initially couldn't make this work when my 'overflow:hidden' element was actually the html tag, so moved this to the '#content' div and it worked just fine. I have been testing on iPad 3 so don't know how bacwards compatible it is.



回答3:

Try this code, it works for me:

var $fixedElement = $('#nav'); // Replace this with your "fixed" element

$fixedElement.css({ "position": "relative" });
window.scroll(0, 0);
$fixedElement.css({ "position": "fixed" });