直接上代码,本例采用了jQuery来进行介绍
CSS部分:
.sticky { position: fixed; top: 0; }
JS部分:
var stickyBar = $('.sticky-bar'); var stickyLine = stickyBar.offset().top; function toggleSticky(e) { window.scrollY > stickyLine ? stickyBar.addClass('sticky') : stickyBar.removeClass('sticky'); } $(document).on('scroll', toggleSticky);