2013-06-26 5 views
4

왼쪽에 사용자와 함께 있어야하는 바가있는 사이트가 있습니다. 그래서 사용자가 스크롤하면 사이드 바가 페이지 상단에서 5px가 될 때까지 스크롤됩니다. 그때부터 그 자리에 고정되어야합니다.'고정'부동 고정/스크롤 사이드 바를 만들려면 어떻게해야합니까?

물론 뷰 포트가 왼쪽 막대보다 작을 수 있으므로 왼쪽 막대가 화면에 완전히 들어 가지 않을 수 있습니다. 그래도 극적이지는 않습니다. 그러나 사용자가 아래쪽으로 스크롤하면 사이드 바의 아래쪽이 페이지의 꼬리말을 '히트'한 다음 페이지와 함께 다시 스크롤하면됩니다.

다음 코드는 내 사이트의 기본적인 설정과 내 질문의 첫 번째 부분입니다 (그러나 작동하지 않는 것을 볼 수 있습니다) : jsfiddle.

질문의 첫 부분은 분명하지만 두 번째 부분은 이해하기가 어려울 수 있으므로 여기는 모형을 사용합니다. when scrolled down 텍스트가 위에 있기 때문에 텍스트가 표시되지 않는 것을 볼 수 있습니다 뷰포트.

$(document).ready(function() { 
    var theLoc = 5; 
    var links = $('#left'); 
    $(window).scroll(function() { 
     console.log('scroll'); 
     if (theLoc >= $(window).scrollTop()) { 
      if (links.hasClass('fixed')) { 
       links.removeClass('fixed'); 
      } 
     } else { 
      if (!links.hasClass('fixed')) { 
       links.addClass('fixed'); 
      } 
     } 
    }); 
}); 

그러나 가능성이 더 CSS 문제 :

여기 부분을 하나 내 시도에 대한 JS있어 나는 등 다시 (높이를 지정하려고

.fixed { 
    position:fixed; 
} 

그것은 매우 큰 것처럼 표시하기 때문에), 그러나 사전에.

+1

체크 아웃이 플러그인 : http://mojotech.github.io/stickymojo/ – Anil

+0

종종 이러한 플러그인이 필요한 것보다 더 많은 옵션을 제공하기 때문에 나 자신을 쓰기에 대해 생각했다. 그럼에도 불구하고, 나는 그것을 시도했다,하지만 난 꽤 내 table'd 레이아웃으로 작동하지 않는 것 같아요 : http://jsfiddle.net/kvVHh/1/ – jdepypere

답변

5

나는 얼마 전에 이것을했는데, 여기에 내가 작성한 코드가있다 : View the JSFiddle.

(마크 업을 약간 변경해야 할 수도 있습니다. 사용자가 갖고있는 레이아웃의 레이아웃이 얼마나 효과가 있을지 모르겠으므로 divs을 사용하여 콘텐츠 레이아웃을 변경하는 것이 좋습니다.), 또는 아래의 코드/로직과 roll your own을 자신 만의 레이아웃으로 사용할 수 있습니다.

기본적으로,
- 페이지로드에있는 사이드 바의 위치
얻기 - - 우리가이 바르가 있으면 우리가 <=을 있는지 window scroll 시험에서, #content.outerHeight()

을 받기를 (이하
우리의 요소를 가져옵니다 원래 sidebarTop position보다 크거나 같음을 확인하거나 blogHeight이 맞는지 확인하고 2가 참이면 스티커 클래스를 제거하고 elseif 스크롤을 >= 원래 sidebar 위치에 넣은 다음 .sticky 클래스를 추가합니다 position: fixed).


자바 스크립트

Check the JSFiddle (Click here)

그렇게 같다 :

// Cache our vars for the fixed sidebar on scroll 
var $sidebar = $('#sidebar-nav'); 

// Get & Store the original top of our #sidebar-nav so we can test against it 
var sidebarTop = $sidebar.position().top; 

// Edit the `- 10` to control when it should disappear when the footer is hit. 
var blogHeight = $('#content').outerHeight() - 10; 

// Add the function below to the scroll event 
$(window).scroll(fixSidebarOnScroll); 

// On window scroll, this fn is called (binded above) 
function fixSidebarOnScroll(){ 

    // Cache our scroll top position (our current scroll position) 
    var windowScrollTop = $(window).scrollTop(); 

    // Add or remove our sticky class on these conditions 
    if (windowScrollTop >= blogHeight || windowScrollTop <= sidebarTop){ 
     // Remove when the scroll is greater than our #content.OuterHeight() 
     // or when our sticky scroll is above the original position of the sidebar 
     $sidebar.removeClass('sticky'); 
    } 
    // Scroll is past the original position of sidebar 
    else if (windowScrollTop >= sidebarTop){ 
     // Otherwise add the sticky if $sidebar doesnt have it already! 
     if (!$sidebar.hasClass('sticky')){ 
      $sidebar.addClass('sticky'); 
     } 
    } 
} 

HTML :

<header>This is the header!</header> 
<ul id="sidebar-nav" class="nav nav-list"> 
    <li><a href="#">Home</a></li> 
    <li><a href="#">Blog</a></li> 
</ul> 
<div id="content">Content in here, scroll down to see the sticky in action!</div> 
<div class="clear"></div> 
<div id="footer">This is the #footer</div> 

C SS :

/* Sticky our navbar on window scroll */ 
#sidebar-nav.sticky {position:fixed;top:5px;} 

/* Other styling for the html markup */ 
header { 
    border:1px solid #aaa; 
    background-color:yellow; 
    margin-bottom:5px; 
    height:50px; 
} 
#sidebar-nav { 
    width:150px; 
    border:1px solid #ddd; 
    margin:0; 
    padding:0; 
    float:left; 
} 
#sidebar-nav li { 
    list-style:none; 
    border:1px solid #ddd; 
    margin:10px; 
    padding:2px; 
} 
#content { 
    height:2000px; 
    width:500px; 
    padding:10px; 
    border:1px solid #ddd; 
    margin:0 0 10px 5px; 
    float:right; 
} 
#footer { 
    height:800px; 
    border:1px solid green; 
    background-color:#ddd; 
} 
.clear { 
    clear:both; 
} 

:)

+0

당신의 마크 업과 함께 작동하는 것,하지만 차라리 사이드 바가 사라지지 않고 대신 바닥 글에 고정되어야합니다! 그러나 JustAnil 플러그인을 사용하여 내 테이블 레이아웃 ('clear'이 마법을 사용함)과 반대되는 페이지 레이아웃을 구현하면 원하는대로 작동하는 것처럼 보입니다. 물론 제공된 코드보다 더 많은 코드를 사용하는 것이 좋습니다. http://jsfiddle.net/dmLQL/1/ – jdepypere

+1

바닥 글을 사라지게하지 않고 바닥에 붙이도록 Javascript를 약간 편집 할 수는 있지만 기꺼이 도와 드릴 수 있습니다! – Anil

+0

@JustAnil 바닥 글을 바닥에 고정 시키려면 어떻게해야할까요? 나는 이것을 스스로 이해하려고 노력하고있다. 이상적으로, 사이드 바가 컨테이너 요소의 끝에 도달 할 때 'bottom'클래스를 추가하고 싶습니다. 나는 비슷한 질문을 여기에 설정 : http://stackoverflow.com/questions/22588635/how-do-i-add-a-stopper-to-this-sticky-sidebar 만약 당신이 좀 걸릴 수 있습니다, 나는 거대하게 고맙습니다. 나는 이것에 잠시 문제가 생겼다. – J82

관련 문제