2017-01-16 62 views
0

我有這個邊欄,哪個位置是通過JS設置的。基本上,它必須在頁面滾動時保持原位,但是,當它到達容器的末端時,它會熄滅。我怎樣才能保持(固定)股利,所以它不會離開集裝箱? 我會在這裏發佈代碼和一張圖片來更好地解釋我在說什麼。固定位置邊欄通過JS

例子:http://www.cosmosgraphicdesign.com/portfolio/work.html?featured

標記:

<div class="container"> 
    <div id="sidebar"> 
     <!-- Sidebar Content --> 
    </div> 

    <div id="mainContent"> 
     <!-- Main Content --> 
    </div> 
</div> 

CSS:

#sidebar{ 
    position: absolute; 
    width: 350px; 
    padding-left: 10px; 
} 

JQuery的:

var mainContent; 
var navbarHeight = $(".navbar").height(); 
var sidebarHeight = $("#sidebar").height()/2; 

$(document).on("scroll", function(){ 
    mainContent = $(".work").scrollTop() + navbarHeight; 

    $("#sidebar").css("top", mainContent); 

    if(mainContent => $(".work").height()){ 
     mainContent = $(".work").scrollTop() + navbarHeight - sidebarHeight; 
     $("#sidebar").css("top", mainContent); 
    } 
}); 
+0

嘗試'background'設置爲你的'.sidebar' .. –

回答

0

這裏是原始的例子,我做了,如果我理解正確的問題:

var mainContentHeight = $("#mainContent").height(); 
    var mainContentTop = $("#mainContent").offset().top; 
    var sidebarHeight = $("#sidebar").height(); 
    var sidebar = $("#sidebar"); 

    $(document).on("scroll", function() { 
    //'stick' sidebar to the bottom of main block if we scroll 'too far' 
    if ($(window).scrollTop() + sidebarHeight > mainContentHeight + mainContentTop) { 
     sidebar.css({ 
     position: 'absolute', 
     top: mainContentHeight - sidebarHeight + mainContentTop 
     }); 
    } 
    //'stick' sidebar to the top of main block 
    else if ($(window).scrollTop() < mainContentTop) { 
     sidebar.css({ 
     position: 'absolute', 
     top: mainContentTop 
     }); 
    } 
    //fixed sidebar until it won't reach top or bottom of the main content block 
    else { 
     sidebar.css({ 
     position: 'fixed', 
     top: 0 
     }); 
    } 
    }); 

Example

+0

感謝雅羅斯拉夫,但在回覆之前我找到了另一個解決方案,謝謝。 它是這裏:https://codepen.io/jovanivezic/pen/ZQNdag –