简体   繁体   中英

Get scroll value on element with position:fixed

I have a page with a header section. In it, two blocks that move sideways after scrolling or dragging on the mobile.

I am trying to set the scrolling for the header, but I want too that the rest of the page stays in place until the side blocks reach left: -50% and right:-50%. I have an event scroll set to header, with pageYoffset values.

I tried to set the rest of the content the page gives to the section with the position:fixed, but then the scroll does not work anymore, and do not count pageYoffset. Do you have any ideas how to get around it, so that the rest of the page would scroll only after the full unveiling of the header? (in short, the pink section should be on top and wait until the header disappears)

let current = $(window).scrollTop();
let windowHeight = $(window).height();
let eleLeft = $(".cd-half-left");
let eleRight = $(".cd-half-right");
let currPositionLeft = eleLeft.position().left;
let currPositionRight = eleRight.position().right;
let headerHeaight = $(".cd-section").height();
let halfBlockWidth = $(".cd-half-block").width();
let windowWidth = $(window).width();


$(window).scroll(function (event) {
    current = $(window).scrollTop();
    console.log({total:total,current:current});

    var newPosition =  ((current / headerHeaight)*100) / 2;

    console.log(newPosition);


    eleLeft.css({left:"-"+newPosition+'%'});
    eleRight.css({right:"-"+newPosition+'%'});
});

FIDDLE

A solution would be not to use window scroll but instead handle scroll gesture (from mousewheel and touchmove) to control left and right panel, and prevent actual scroll when the panels are not fully opened.

so instead of $(window].scroll(handler) , try with $('.cd-block').bind('mousewheel', handler) and $('.cd-block').bind('mousewheel', handler)

The handler being:

function updateCurrent(event) {
    if (current >= 50) {
        current = 50;
    } else {
        if (current <= 0) {
            current = 0;
        }
        // if below 50 we cancel the event to prevent the scroll
        event.originalEvent.preventDefault();
    }

    eleLeft.css({left:"-"+current+'%'});
    eleRight.css({right:"-"+current+'%'});
}

Here is a buggy but working solution (keyboard space, up and down should be handled too):

fiddle

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