jQuery代码更改滚动元素的位置

Ahm*_*uad 3 css jquery position

我有一个酒吧,其中包括分享和社交图标.现在这个栏位于帖子标题下面,如下所示:

<div class="post" id="post-<?php the_ID(); ?>">

            <div class="title">
                <h1><?php the_title(); ?></h1>
            </div>

            <div class="sharelinks">
                <ul>
                    <li><a href="https://twitter.com/share" class="twitter-share-button" data-url="<?php the_permalink(); ?>" data-text="<?php the_title(); ?>" data-count="horizontal">Tweet</a></li>
                    <li><div class="fb-like" data-href="<?php the_permalink(); ?>" data-send="false" data-layout="button_count" data-show-faces="false" data-font="arial"></div></li>
                    <li><g:plusone size="medium" href="<?php the_permalink(); ?>/"></g:plusone></li>
                    <li><a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo urlencode(sofa_image_src('full')); ?>&description=<?php echo urlencode(get_the_title($post->ID)); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a></li>
                    <li><su:badge layout="1"></su:badge></li>
                </ul>
            </div>
</div>
Run Code Online (Sandbox Code Playgroud)

那是我的HTML.而我对"sharelinks"的css是:

.sharelinks {
    padding: 10px 20px;
    background: #f1f1f1;
    box-shadow: 0 1px #fff inset, 0 -1px #fff inset;
    border-bottom: 1px solid #ddd;
    position: relative;
}
Run Code Online (Sandbox Code Playgroud)

我想要实现什么? - 当用户滚动超出其范围并将其始终放在页面顶部(固定位置)时,我想更改sharelinks div的位置,然后当用户向后滚动到其位置时使其返回到其默认位置.这个想法是如果条形图出现在它的位置,只要用户不滚动"超出"它,如果他滚动它,它看起来固定在页面顶部.

我有一个类似的代码,适用于HEADER,但相同的代码不适用于此元素,我认为因为我的标题位于页面的最顶层.

我真的需要任何帮助或想法如何实现我所追求的效果.

// fixed navigation
var yOffset = $("#header").offset().top;
$(window).scroll(function() {
    if ($(window).scrollTop() > yOffset) {
        $("#header").css({
            'top': 0,
            'position': 'fixed'
        });
    } else {
        $("#header").css({
            'top': yOffset + 'px',
            'position': 'absolute'
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

Ahm*_*uad 9

这是固定的解决方案.:)

它首先获取滚动位置,然后在滚动传递特定值(顶部到元素开始之间的距离)时将元素的CSS更改为固定,否则恢复元素的默认css.

var sOffset = $(".sharelinks").offset().top;
var shareheight = $(".sharelinks").height() + 43;
$(window).scroll(function() {
    var scrollYpos = $(document).scrollTop();
    if (scrollYpos > sOffset - shareheight) {
        $(".sharelinks").css({
            'top': '61px',
            'position': 'fixed'
        });
    } else {
        $(".sharelinks").css({
            'top': 'auto',
            'position': 'relative'
        });
    }
});
Run Code Online (Sandbox Code Playgroud)