简体   繁体   中英

Stick div on screen when user is scrolling

I want to make my div right to stick on screen when user is scrolling. This is example situation: https://jsfiddle.net/gwjehuzf/

I tried a lot, but without success. Something like this:

$(window).scroll(function () {

    if ($(document).scrollTop() > 400) {
        console.log("a");
        var newPos = $(document).scrollTop() + 400;
        $('.right').css({ top: newPos });
    }

    else {
        $('.right').css({ top: 400 });
    }
})

for some reason is not working. Any ideas?

just use css .right{position:sticky; top:0; overflow:hidden;}

Just need to add few CSS , we'll resolve your issue. Thanks

.right {
  position: fixed;
  right: 0;
  width: calc(100% - 200px);
}

Add this css in your code

 .right { position: sticky; top: 5px; } 

No JavaScript needed for that. Use position: fixed for the .right div.
If it disappears, give it a width (maybe about 80%) and right: 0 :

.right {
    position: fixed;
    width: 80%;
    right: 0;
}

You can achieve this by adding position: sticky to .right and setting top: 0 .

.right {
  position: fixed;
  top: 0;
}

Your JSFiddle corrected here .

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