jQuery
【jQuery】スクロールされるとページの要素を固定するScrollToFixed
September 19, 2018

ScrollToFixedは垂直スクロールし、目標位置に到達するとページ上の要素を固定させ、目標位置を超えて戻ると、要素はページ上の元の位置に戻るプラグイン。
Default options:
$(document).ready(function() { $('#mydiv').scrollToFixed(); });
マージンとリミットのオプション
$(document).ready(function() { $('#cart').scrollToFixed({ marginTop: 10, limit: $($('h2')[5]).offset().top }); });
固定ヘッダーと固定フッター
// The fixed footer will go unfixed to reveal whatever is below it when scrolled // past the limit. $(document).ready(function() { $('.header').scrollToFixed(); $('.footer').scrollToFixed( { bottom: 0, limit: $('.footer').offset().top } ); });
Example
$(document).ready(function() { $('.header').scrollToFixed({ preFixed: function() { $(this).find('h1').css('color', 'blue'); }, postFixed: function() { $(this).find('h1').css('color', ''); } }); $('.footer').scrollToFixed( { bottom: 0, limit: $('.footer').offset().top, preFixed: function() { $(this).find('h1').css('color', 'blue'); }, postFixed: function() { $(this).find('h1').css('color', ''); } }); // Order matters because our summary limit is based on the position // of the footer. On window refresh, the summary needs to recalculate // after the footer. $('#summary').scrollToFixed({ marginTop: $('.header').outerHeight() + 10, limit: function() { var limit = $('.footer').offset().top - $('#summary').outerHeight(true) - 10; return limit; }, zIndex: 999, preFixed: function() { $(this).find('.title').css('color', 'blue'); }, preAbsolute: function() { $(this).find('.title').css('color', 'red'); }, postFixed: function() { $(this).find('.title').css('color', ''); }, postAbsolute: function() { $(this).find('.title').css('color', ''); } }); });
// returns whether or not the ScrollToFixed plugin has been applied to the element. var b = $.isScrollToFixed('.header');
$('.header').trigger('detach.ScrollToFixed'); // Removes scrollToFixed from the element. The // namespace ensures remove will not be called // on other plugins that may be listening for // that event! NOTE: Renamed as "detach" to // avoid the new Chrome native "remove" method. $('.header').trigger('resize'); // Resizes the spacer in case the fixed element height changes. // Good for size changes to the fixed element. $(window).scroll(); // Causes the plugin to recalculate the window scoll. // Good for layout changes that could change the fixed element's response to // the scroll. Example: the fixed element height expands which should cause // it to invoke its limit. $(window).resize(); // Causes the plugin to recalculate the element offsets, then the window scroll. // Good for layout changes that could cause the fixed element to move. // Example: the header height increases which should cause the fixed // element to fix at a greater vertical scroll position.