简体   繁体   中英

Recreating Chrome iOS scrolling navigation bar effect in jquery/javascript

I'm trying to achieve a similar effect to the way the iOS Chromes navigation bar scrolls and hides, the comes back into view when scrolling up.

This JSfiddle is where I am so far.

var pos = $(window).scrollTop(),
header = $("header");

$(window).scroll(function () {
var newPos = $(this).scrollTop();

if (newPos > pos) { //down 
    header.css('top', -(newPos) + 'px');
    if (pos > 40) {
        header.css('top', '-40px');
    }
} else { //up
    header.css('top', '0');
}


pos = newPos;

$(".last span").html(pos);
$(".new span").html(newPos);
});

So the header scrolls up as you scroll down, but I can't work out how to scroll it back into view in the way I want. Tried using animate() which gave me a scroll in and out, but the animation wasn't smooth. I' want the header to move at the same speed as as the scroll, any ideas?

I've a similar problem to achive the same effect, maybe this could help you: Slide header up if you scroll down and vice versa . It would be great to get see some "nerdy" people who can get this to work?!

To make it as you noted (the animating way), you could try something like this: http://jsfiddle.net/yckart/jzRfv/

However, I think it would be much nicer to get this working!

CSS

header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 128px;
    background: tomato;
    -webkit-transition: top 0.5s
}

JS

// something simple to get the current scroll direction
// false === down | true === up
var scrollDir = (function (oldOffset) {
    return function (offset) {
        var dir = offset < oldOffset;
        oldOffset = offset;
        return dir;
    };
}());


var header = document.querySelector('header');
addEventListener('scroll', function () {
    var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
    header.style.top = -(scrollDir(scrollY) ? 0 : header.clientHeight/2) + 'px';
});

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