简体   繁体   中英

How to toggle a fixed position class on a div on scroll?

I've been trying for ages to fix this div to the top of my screen when I scroll to it, but it's not working for some reason. Upon searching many answers, I think it might be because $(window).height() returns inaccurate values on Chrome.

What I'm trying to accomplish on my website is for a block of text to stick (fix) at the middle of the window when I scroll down to it, and then unfix later on in the page when the bottom of it gets inline with an image. I will be doing this by vertically aligning the text in a transparent div that is the same height as the viewport (100vh) that will fix when it reaches the top of the screen, and unfixing it when the bottom of this div touches the top of another transparent div that starts as the image ends.

The solution must be responsive, since I'm planning for the website to go on all platforms. Any help would be appreciated. Here is the code I have - it just doesn't work for me:

JQuery

$(document).ready(function() {
    var s = $("#words_box");
    var pos = s.position();                    
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();

        if (windowpos <= pos.top) {
            s.addClass("fix");
        } else {
            s.removeClass("fix"); 
        }
    });
});

HTML

<div id="words_box">

    <h2 id="about_words">Lorem ipsum dolor sit amet, consectetur adipiscing elit...
    </h2>

</div>

<img id="about_words" src="any image that takes up the right side of the viewport."/>

CSS

#about_words {
    float:left;
    margin-right: 52.5%;
    font-size:2.17vw;
    text-align:left !important;
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}   

#words_box {
    height: 100vh;
    text-align:center;
    float:left; 
    margin-top:-10.4em;
    position:static;
    z-index:-10000;
}

.fix{
    position:fixed !important;
    margin-right: 5.555555%;
    top:10.4em;
}

I've found what was going wrong, if you were wondering. It was an issue with Google Chrome, since the jQuery was working in Safari but not Chrome. I fixed it by replacing

$(document).ready(function() { 

with

$(window).on('load', function() {

Now the div does fix to the top when I add the class .fix to it.

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