3

Javascript コード.offset.topを使用して要素を修正していますが、別の要素に到達したら終了したいと考えています。

<script>
    $(document).ready(function (){
        var sidebartop = $('.single-content').offset().top;
        $(window).scroll(function (event){
            var y = $(this).scrollTop();
            if ( y>= sidebartop ){
                $('#sharing-links').addClass('fixed');
            } else {
                $('#sharing-links').removeClass('fixed');
            }
        });
    });
</script>

これはhtmlです

    <div id="sharing-links">
    <!-- this is the fixed element -->
</div>
<div class="single-content">
    <!-- when the div reaches here is adds the .fixed -->
    <div class="div2">
        <!-- I want the fixed element to end when it reaches this div -->
    </div>
</div>

誰もそれを修正する方法を知っていますか?

4

1 に答える 1

1

この件に関しては多くの関連する質問があります。多くのトリック、機能するもの、うまくいかないものがありますが、スクロールして修正するときは、この正確な問題を解決するために作成されたこの jquery プラグインを常に使用します。

デモ:

http://jsfiddle.net/ZczEt/167/ http://jsfiddle.net/y3qV5/434/ http://jsfiddle.net/k2R3G/81/

プラグインとソース

https://github.com/bigspotteddog/ScrollToFixed

使用法:

$(document).ready(function() {
  $('#mydiv').scrollToFixed();
});

編集:

その線だけを探している場合は、これを使用して.single-content上部を計算する必要があります。

$(document).ready(function (){
    var auxtop = $('.single-content').offset().top 
    var margintop = parseFloat($('.single-content').css('margin-top').replace(/auto/, 0));
    var sidebartop = auxtop - margintop;
    $(window).scroll(function (event){
        var y = $(this).scrollTop();
        if ( y>= sidebartop ){
            $('#sharing-links').addClass('fixed');
        } else {
            $('#sharing-links').removeClass('fixed');
        }
    });
});
于 2013-11-09T04:40:51.267 に答える