简体   繁体   中英

How would I go about adding a top offset for an element that sticks when it hits the top of the window?

I want a sharing wrapper to stick to the top of the window when it reaches the top on scroll. It just appends a sticky class to the element with a fixed position. However, how would I go about adding an offset to the top? I have a fixed header that's 60px in height and currently the div is sticking to the very top of the window, hiding the top 60px of it. Instead, I want it to stick 60px from the top of the window.

My JS:

(function () {
    var $stickyShare, $window, top;
    $window = $(window);
    $stickyShare = $('.share-container');
    top = $stickyShare.offset().top;
    $window.scroll(function () {
        return $stickyShare.toggleClass('sticky-fixed', $window.scrollTop() > top);
    });
}.call(this));

A JSfiddle: http://jsfiddle.net/h6afrtpk/1/

You can update your .sticky-fixed class to set top to 60px instead of 0.

.share-container.sticky-fixed {
    position: fixed;
    top: 60px;
    left: auto;
    right: auto;
    background-color: #fff;
    border-bottom: 1px solid #ccc;
}

And update the function to check against top - 60.

return $stickyShare.toggleClass('sticky-fixed', $window.scrollTop() > top - 60);

A 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