2014-03-21 2 views
11

Vice.com에서와 같은 기능을하는 사이드 바를 만들려고합니다. 아래로 스크롤하면 사이드 바가 특정 지점에서 고정되고 사이드 바가 사이트 하단 근처의 특정 지점에 도달하면 나머지 사이트와 계속해서 위로 스크롤됩니다.고정 된 사이드 바 스크롤을 페이지 하단에서 290 픽셀로 만드시겠습니까?

내 사이트에서 사이드 바가 아래쪽에 도달하면 계속해서 사이드 바를 가져 오는 두 번째 부분에 붙어 있습니다. 290px 정확한 것입니다. 여기

는 내가 지금까지 무엇을 가지고 :

자바 스크립트

<script> 
jQuery(window).scroll(function() { 
    var threshold = 20; 
if (jQuery(window).scrollTop() >= 20) 
    jQuery('#sidebar').addClass('fixed'); 
else 
    jQuery('#sidebar').removeClass('fixed'); 
}); 
</script> 

CSS

#sidebar { 
    margin: 0; 
    position: absolute; 
    right: 0; 
    width: 220px; 
} 
#sidebar.fixed { 
    margin-left: 720px; 
    position:fixed; 
    right: auto; 
    top: 173px; 
} 

나는 하단에 특정 지점을 명중하면 고정 사이드 바는 스크롤 할 수있는 방법 ?


편집 # 여기에 1

아담에 의해 업데이트 된 코드입니다. 다른 임계 값이있는 페이지에 대해 조건문을 사용하고 있습니다. 이 코드를 사용할 때 아무 것도 일어나지 않습니다. 즉, 사이드 바에 fixed 클래스가 추가되지 않으므로 코드가없는 것처럼 정상적으로 스크롤됩니다. 또한,이 라인에 콘솔 오류가 나타납니다 if (scrollTop() >= 236) { "숫자는 함수가 아닙니다"라고 말합니다.

if (jQuery(document.body).hasClass("home")) { 

    jQuery(window).scroll(function() { 
     var sidebarHeight = jQuery('#sidebar').height(), 
      containerHeight = jQuery('#container').height() + 173, 
      scrollTop = jQuery(window).scrollTop(), 
      clientHeight = scrollTop + jQuery(window).height(), 
      threshold = 654; 
     if (scrollTop() >= 654) { 
      jQuery('#sidebar').addClass('fixed'); 
     } else if (containerHeight - scrollTop <= sidebarHeight) { 
      jQuery('#sidebar').removeClass('fixed').addClass('bottom'); 
     } 
    }); 

} else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) { 

    jQuery(window).scroll(function() { 
     var sidebarHeight = jQuery('#sidebar').height(), 
      containerHeight = jQuery('#container').height() + 173, 
      scrollTop = jQuery(window).scrollTop(), 
      clientHeight = scrollTop + jQuery(window).height(), 
      threshold = 20; 
     if (scrollTop() >= 20) { 
      jQuery('#sidebar').addClass('fixed'); 
     } else if (containerHeight - scrollTop <= sidebarHeight) { 
      jQuery('#sidebar').removeClass('fixed').addClass('bottom'); 
     } 
    }); 

} else { 

    jQuery(window).scroll(function() { 
     var sidebarHeight = jQuery('#sidebar').height(), 
      containerHeight = jQuery('#container').height() + 173, 
      scrollTop = jQuery(window).scrollTop(), 
      clientHeight = scrollTop + jQuery(window).height(), 
      threshold = 236; 
     if (scrollTop() >= 236) { 
      jQuery('#sidebar').addClass('fixed'); 
     } else if (containerHeight - scrollTop <= sidebarHeight) { 
      jQuery('#sidebar').removeClass('fixed').addClass('bottom'); 
     } 
    }); 

} 

다음은 요청에 따라 HTML 구조입니다 :

<!-- BEGIN #masthead--> 
<div id="masthead"> 
    <!-- #secondary-menu --> 
    <div id="secondary-menu"> 

     <!-- .centered-menu --> 
     <div class="centered-menu"> 
      <div class="latest-tweets"></div> 
      <div id="search-bar"></div> 
      <ul class="social-icons sf-js-enabled"></ul> 
     </div> 
     <!-- /.centered-menu --> 

    </div> 
    <!-- /#secondary-menu --> 

    <!-- BEGIN #header--> 
    <div id="header"> 

     <!-- #header-inner --> 
     <div id="header-inner" class="clearfix"> 
      <div id="logo"></div> 

      <!-- BEGIN #primary-menu --> 
      <div id="primary-menu" class="clearfix"> 

       <!-- .left-menu --> 
       <div class="left-menu split-menu"></div> 
       <!-- /.left-menu --> 

       <!-- .right-menu --> 
       <div class="right-menu split-menu"> 
        <div class="menu-menu-right-container"></div> 
       <!-- /.right-menu --> 

      <!-- END #primary-menu --> 
      </div> 

     </div> 
     <!-- /#header-inner --> 

    <!-- END #header --> 

    <!-- BEGIN #mobile-menu --> 
    <div id="mobile-menu"> 
     <div id="mobile-inner"></div> 
    </div> 
    <!-- END #mobile-menu --> 

    </div> 

    <div id="categories-bar"></div> 

</div> 
<div id="masthead-space"></div> 
<!-- END #masthead --> 

<!-- BEGIN #wrapper--> 
<div id="wrapper"> 

    <!-- BEGIN #page--> 
    <div id="page"> 

     <div id="main" class="clearfix"> 

      <div id="container" class="clearfix"> 

       <!--BEGIN #content --> 
       <div id="content"> 
        <div id="sidebar"></div><!-- #sidebar --> 
       </div> 

      </div> 

     <!--END #main --> 
     </div> 

    <!--END #page --> 
    </div> 

<!--END #wrapper --> 
</div> 

<!--BEGIN #bottom --> 
<div id="bottom"> 

    <!--BEGIN #footer --> 
    <div id="footer"></div> 

</div> 
+0

나는 당신의 페이지의 구조에 긍정적 인 아니에요하지만 난 그것이 작동되도록하려고합니다. 당신이 나에게 바이올린을 만들 수 있다면 나는 더 정확하게 나를 할 수 있었다. –

답변

0

내가 지금 HTML의 구조를 볼 수 없기 때문에 내 댓글에이 꺼져있을 수 있습니다 말했듯이. 그러나 이것과 같은 것이 효과가있다. scrollbar, container (헤더의 높이), 사용자가 볼 수있는 영역의 높이 또는 client의 높이를 얻습니다. 따라서 수학을 사용하면 container - scrollTopscrollbar 높이보다 작 으면 고정을 중지하기 위해 스크롤 막대가 필요하다고 말할 수 있습니다. 이 시점에서 우리는 고정 클래스를 제거하고 단지 하나의 속성을 가진 하단 클래스를 추가합니다. bottom: 0. 이제 스크롤 막대가 컨테이너 내부에 있고 컨테이너에 position: relative이있는 한 컨테이너의 바닥에 고정됩니다.

자바 스크립트 :

jQuery(window).scroll(function(){ 
    var sidebarHeight = jQuery('#sidebar').height(), 
     containerHeight = jQuery('#container').height() + 173, 
     scrollTop = jQuery(window).scrollTop(), 
     clientHeight = scrollTop + jQuery(window).height(), 
     threshold = 20; 
    if(scrollTop >= 20){ 
     jQuery('#sidebar').addClass('fixed'); 
    }else if(containerHeight - scrollTop <= sidebarHeight){ 
     jQuery('#sidebar').removeClass('fixed').addClass('bottom'); 
    } 
}); 

CSS :

#sidebar.bottom { 
    bottom: 0; 
} 

이 당신을 위해 작동하지 않는 경우 알려줘 등이가 더 할 수있는 HTML을 가지고 질문을 업데이트하여 필요합니다. 또한 사용자가 페이지를 백업하는 것을 처리해야 할 것입니다. 이는 현재로서는 설명하지 않지만 추가하기가 어렵지는 않습니다.

0

bootstrap-affix를 살펴보십시오.JS http://getbootstrap.com/2.3.2/javascript.html#affix 그것은 행동 추가-속성 데이터 당신이 요구하는, 당신은 HTML5를 사용하여 정확히 않습니다

:

<div data-spy="affix" data-offset-top="200">...</div> 
+0

나는 이것을 조사해 보았는데 알아 내지 못합니다. 나는 불행하게도 부트 스트랩에 대해 많이 알지 못한다. 그러나 이것이 내가 원하는 것을하는 것처럼 보인다. – J82

+0

죄송합니다. 지금은 답변을 향상시킬 수 없습니다. 모바일에 있습니다. 링크는 이전 버전의 부트 스트랩에 대한 것이므로 최신 지침은 http://getbootstrap.com/javascript/을 참조하십시오. –

0

것은이 코드를 시도를 (내가 사용하는 ID의 마크 업에 따라) :

function sidebarScroll() 
{ 
    var tmpWindow = $(window), 
     wrapper = $('#wrapper').height(), 
     header = $('#header').height(), 
     sidebar = $('#sidebar'), 
     offsetTop = sidebar.offset().top, 
     offsetBottom; 

    tmpWindow.scroll(function(){ 

    offsetBottom = (wrapper + header) - sidebar.height(); 

    if (tmpWindow.scrollTop() < offsetTop) { 
     sidebar.removeClass('fixed bottom'); 
    } else if (tmpWindow.scrollTop() > offsetBottom) { 
     sidebar.removeClass('fixed').addClass('bottom'); 
    } else { 
     sidebar.removeClass('bottom').addClass('fixed'); 
    } 
    }); 
} 

sidebarScroll(); 

이이 클래스 당신이 필요합니다

#wrapper { 
    position: relative; 
} 
#sidebar { 
    width: 220px; 
    position: absolute; 
    right: 0; 
} 

#sidebar.fixed { 
    position: fixed; 
    top: 0; 
} 

#sidebar.bottom { 
    position: absolute; 
    bottom: 0; 
} 

DEMO

0

아담으로부터 빌린 코드가 잘못 복사되었습니다. scrollTop 대신 scrollTop()을 사용합니다. scrollTop이 숫자로 설정되어 있기 때문에 본질적으로 20() (또는 scrollTop이 설정된 숫자)

편집 : 코드의 중복성을 줄이기 위해 필자는 임계 값은 경우 문 삼항를 통해 설정 :

jQuery(window).scroll(function() { 
    var sidebarHeight = jQuery('#sidebar').height(), 
    containerHeight = jQuery('#container').height() + 173, 
    scrollTop = jQuery(window).scrollTop(), 
    clientHeight = scrollTop + jQuery(window).height(), 
    threshold = (jQuery(document.body).hasClass("home"))?654:((jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page"))?20:236); 
}); 
0
<div class="main"> 
</div> 
<div class="foot"> 
</div> 
<div id="float"> 
<div class="float_content_head"> 
I was sending javascript to display 
</div><div class="float_content"> 
d my issue was that I was sending javascript to display console messages. Even when I looked at the file in my browser (not through the application) it showed exactly as I expected it to (eg the extra tags weren't showing), but there were showing in the html/text output and were trying to be parsed. Hope this helps someone!I had a similar problem, and my issue was that I was sending tags we 
</div> 
</div> 

Css 
<style type="text/css"> 
#float{ 
    background: #fff; 
    position:absolute; 
    right:30px; 
    top:20px; 
    width:250px; 
    padding:10px; 
    border-radius: 6px; 
    -webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.43); 
-moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.43); 
box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.43); 
} 
.float_content_head{ 
    padding:10px; 
    border-bottom: 1px solid #efefef; 
    text-align:center; 
} 
.float_content{ 
    padding-top:10px; 
} 
.main{ 
    width: 800px; 
    height: 800px; 
    margin: 0 auto; 
    border:1px solid #efefef; 
    padding: 10px; 
    background:#ccc; 
} 
.foot{ 
    width: 100%; 
    height: 800px; 
    margin: 0 auto; 
    border:1px solid #efefef; 
    padding: 10px; 
    background:#096; 
} 
#box p{ 
    margin:0; 
    padding:0; 
} 
</style> 

JS 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
var starting_position = $('#float').offset(); 
var top_padding = 50; 
var bottom_limit = $('.foot').offset(); 
var box_height = $('#float').height() + 20; 
$(window).scroll(function(){ 
var top_window = $(window).scrollTop(); 
if (top_window > starting_position.top && top_window < bottom_limit.top - box_height){ 
$('#float').stop().animate({top: top_window - starting_position.top + top_padding}, 400); 
} else if (top_window > bottom_limit.top - starting_position.top - box_height){ 
$('#float').stop().animate({top: bottom_limit.top - starting_position.top - box_height }, 400); 
} else { $('#float').stop().animate({top: 10 }, 400);   
} 
}); 
}); 
</script> 
+0

Please OP에 도움이되는 설명을 코드에 추가하면 동일한 문제가있는 사람도 누구나 솔루션을 이해할 수 있습니다. – chopper

0

이 (내 ID를 변명) this is what you're after 같은 소리 :

$(document).ready(function() { 
// Get the inital position of the menu 
    var initialPos = $('#mainnav').offset().top; 

//Bind scrolling or resizing 
$(window).bind('scroll resize', function() { 

// Get the distance from the top of the page to the top of the footer 
    var footerTop = $('#footer').length > 0 ? $('#footer').offset().top : $('#footer').offset().top; 

// Get the distance from the top of the page to the bottom of the menu 
    var navBottom = $(window).scrollTop() + $('#mainnav').height() + 22; 

// If the user scrolls further than the height of the header (this method allows for resizing with a max-width layout) 
    if ($(window).scrollTop() > initialPos) { 
     $('#mainnav').css({ 
      'position': 'fixed', 

      // move the menu based on how far the user has scrolled, and if it exceed the height of the footer 
      'top': (footerTop - navBottom > 0 ? 0 : footerTop - navBottom) + 'px', 
      'left': ($('#wrapper02').offset().left - $(window).scrollLeft()) + 'px' 
     }); 
    } else { 
     $('#mainnav').css({ 
      'position': 'static' 
     }); 
    } 
}); 
}); 
0
<style> 

    #wrap { 
    width:100%; 
    height:1000px; 
} 
#sidebar { 
    width:100px; 
    height:100px; 
    float:left; 
    background-color:black; 
    color:white; 
    vertical-align:middle; 
    text-align:center; 
} 
    </style> 

    <script> 
    var offset = $("#sidebar").offset(); 
var topPadding = 15; 

$(window).scroll(function() { 
    if ($(window).scrollTop() > offset.top) { 
     $("#sidebar").stop().animate({ 
      marginTop: $(window).scrollTop() - offset.top + topPadding 
     }); 
    } else { 
     $("#sidebar").stop().animate({ 
      marginTop: 0 
     }); 
    } 
}); 

    </script> 

    <div id='wrap'> 
     <div id="sidebar">Side Bar</div> 
    </div> 
+0

제공하는 솔루션에 대한 설명을 추가하여 답을 더 자세히 설명해 주시겠습니까? – abarisone

+0

실행하면 모든 설명이 제공됩니다. –

+0

https : // jsfiddle.net/c5kqudo2/5/ –

0

옵션은 waypoints.js가 될 수 있지만, 간단한 jQuery로 할 수 있다고 생각합니다. 웨이 포인트가 도움이 될 수도 있고 그렇지 않을 수도 있지만 ...이 시나리오에서 사용할 수 있습니다. 그래서 옵션입니다. 여기

Waypoints.js : http://imakewebthings.com/waypoints/

1

내 조언 :

원하는 특성을 가진 2 개 CSS 클래스를 만들고 모두 중단 점에 도달 한 후, 1은 시작에서 활성화되어야합니다 전환.

FIDDLE

JS

var changePoint = $('#reaching_the_top_of_this_element_activates_change').offset().top; 

$(window).scroll(function() { 
if ($(window).scrollTop() >= changePoint) { 
    $('#sidebar').removeClass('blackStatic'); 
    $('#sidebar').addClass('redFixed'); 
} 
else { 
    $('#sidebar').addClass('blackStatic'); 
    $('#sidebar').removeClass('redFixed'); 
} 

}); 내 대답은 조금 꺼져의 나 때문에

CSS는

.blackStatic { 
    position: static; 
    background-color: black; 
    color: red; 
} 
.redFixed { 
    position: fixed; 
    top: 0; 
    background-color: red; 
    color: black; 
}