简体   繁体   中英

How should I force an element to remain fixed with parallax scrolling?

Abridged Codepen below. I'm trying to model a page after this BBC article from way back, but I can't seem to get my image to go to position fixed based off scrolling.

I'm thinking that if I can get the element to be position: fixed then I can swap out the images with js

I can't seem to get my yPosition var to pass through my scroll function though http://codepen.io/spkellydev/pen/aWzwdQ?editors=1111

Here's the fuller codepen of the project, I just can't seem to get this js to work for me. Any tips?

here's my JS

var yPosition = document.getElementById("scrollLock").offsetTop;



window.onscroll = function(){ // scrolling fires this function      
console.log(yPosition);
    var myElement = document.getElementById("scrollLock"); // for cleaner code

    // compare original y position of element to y position of page
  console.log('it is scrolled at');
    if( yPosition < window.pageYOffset ){ 

        // snap element to the top by changing css values of element
        myElement.addClass('addScrollLockImg'); 
        console.log('it worked');
     } else {          

        // re-position to original flow of content
       myElement.removeClass('addScrollLockImg');
       console.log('it passed');
    }               
}      

Have you tried using position: sticky ?

This doesn't directly answer your question but will produce exactly what you are looking for. Sticky is not fully supported though .

position: -webkit-sticky
position: sticky
top: 20px /* Distance from top of screen when 'stuck' */

This is all you need and it will keep it's place on the screen where the parent element allows. As in it will not move outside of it's parent element.

Your CodePen edited (I may have messed up some of your CSS)

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