2017-02-05 3 views
0

Я создал эту боковую панель, которая торчит, когда нижняя часть div достигает ее нижней. Тем не менее, кажется, мерцает, когда я прокручиваю. Не могли бы вы помочь, что я делаю неправильно?Липкая боковая панель мерцает во время прокрутки

HTML

<div id="header"></div> 
<div id="stickymain"> 
    <div class="side" id="stickyside"> 
     <p> 
     This is the best we could do and there's nothing more one could expect from here to carry from onwards. I think there's nothing better too. 
     </p> 
     <p> 
     This is the best we could do and there's nothing more one could expect from here to carry from onwards. I think there's nothing better too. This is the best we could do and there's nothing more one could expect from here to carry from onwards. I think there's nothing better too. This is the best we could do and there's nothing more one could expect from here to carry from onwards. I think there's nothing better too.11 
     </p> 
    </div> 
    <div class="main"></div> 
    <div class="main"></div> 
    <div class="main"></div> 
    <div class="main"></div> 
    <div class="main"></div> 
</div> 
<div id="footer"></div> 
<script> 

CSS

body { 
    margin: 0; 
    padding: 10px; 
} 
#header { 
    height: 100px; 
    margin: 0 0 10px; 
    background: red; 
} 
#content { 
    position: relative; 
    float: left; 
    width: 100%; 
    height: auto; 
    margin: 0 -110px 0 0; 
} 
.side { 
    float: right; 
    width: 100px; 
    /* min-height: 500px; */ 
    margin: 0 0 0 10px; 
    background: linear-gradient(red, yellow); 
} 
.main { 
    height: 600px; 
    margin: 0 110px 10px 0; 
    background: lightgray; 
} 
#footer { 
    clear: both; 
    height: 100px; 
    background: orange; 
} 

JS

jQuery(document).ready(function() { 
       jQuery.fn.stickyTopBottom = function(){ 
        var options = { 
         container: jQuery('#stickymain'), 
         top_offset: 0, 
         bottom_offset: 0 
        }; 
        console.log(options); 
        let jQueryel = jQuery(this) 

        let container_top = options.container.offset().top 
        let element_top = jQueryel.offset().top 

        let viewport_height = jQuery(window).height() 
        jQuery(window).on('resize', function(){ 
         viewport_height = jQuery(window).height() 
        }); 



        let current_translate = 0 
        let last_viewport_top = document.documentElement.scrollTop || document.body.scrollTop 
        jQuery(window).scroll(function(){ 
         var viewport_top = document.documentElement.scrollTop || document.body.scrollTop 
         let viewport_bottom = viewport_top + viewport_height 
         let effective_viewport_top = viewport_top + options.top_offset 
         let effective_viewport_bottom = viewport_bottom - options.bottom_offset 


         let element_height = jQueryel.height() 

         let is_scrolling_up = viewport_top < last_viewport_top 
         let element_fits_in_viewport = element_height < viewport_height 

         let new_translation = null 
         if (is_scrolling_up){ 
          if (effective_viewport_top < container_top) 
           new_translation = 0 
          else if (effective_viewport_top < element_top + current_translate) 
           new_translation = effective_viewport_top - element_top 
         }else if (element_fits_in_viewport){ 
          if (effective_viewport_top > element_top + current_translate) 
           new_translation = effective_viewport_top - element_top 

         }else { 
          let container_bottom = container_top + options.container.height() 
          if (effective_viewport_bottom > container_bottom) 
           new_translation = container_bottom - (element_top + element_height) 
          else if (effective_viewport_bottom > element_top + element_height + current_translate) 
           new_translation = effective_viewport_bottom - (element_top + element_height) 
         } 
         if (new_translation != null){ 
          current_translate = new_translation; 
          console.log('i am here at css'); 

          jQueryel.css('transform', ('translate(0, '+current_translate+'px)')); 
         } 
         last_viewport_top = viewport_top 
        }); 
       } 
       jQuery('#stickyside').stickyTopBottom(); 
      }); 

для выдачи мерцающим исключением случаев, когда я прокручиваю, все остальное работает именно так, как я хочу. Я нахожусь на Mac с помощью Chrome, Firefox и Safari.

CodePen Demo

+0

Извините, я не очень хорошо понимаю ожидаемый результат. Боковая панель должна быть зафиксирована или зафиксирована при достижении ее вершины? – Massimo

+0

Нет, когда он достигает нижней части боковой панели, он должен придерживаться. Как показано точно. Тем не менее, боковая панель вместо того, чтобы прилипать, она «мерцает», когда я прокручиваю дальше вниз. –

+0

Попробуйте прокрутить, и вы заметите мерцающий эффект, который я не хочу. –

ответ

0

Вместо того, чтобы использовать только Javascript, чтобы сделать всю работу, вы можете использовать свойства CSS, чтобы помочь вам.

Вы можете просто изменить положение свойство боковой панели при достижении определенной точки видового экрана:

$(window).scroll(function() { 
    var sTop = $(this).scrollTop(); 
    var footerTop = $('#footer').offset().top; 
    var sideHeight = $('.side').height(); 
    var headerHeight = $('#header').height(); 

    if(sTop > headerHeight + (sideHeight/2)) { 
     $('.side').css({ 
     position:'fixed', 
     bottom:'10px' 
     }); 
    } else { 
     $('.side').css({ 
     position:'absolute', 
     bottom:'inherit' 
     }); 
    } 
}); 

PEN Смотреть это

Я надеюсь, что это один, это нормально! :)

+0

Ваше решение касается только сверху, чего я не хочу. То, что я хочу, это полная противоположность: как мне заставить боковую панель остановиться, когда она достигает дна ?! Спасибо хоть. –

+0

Да, я знаю. Вот почему я написал: «Я сделал эту функцию только для верхней части боковой панели»: D Я дам полное решение через некоторое время. – Matteo

+0

Спасибо. Это было бы потрясающе :) –

Смежные вопросы