jquery.fixed.sidebar.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. (function ($) {
  2. $.fn.stickySidebar = function (options) {
  3. var config = $.extend({
  4. headerSelector: '#header',
  5. navSelector: '#nav',
  6. contentSelector: '#content',
  7. footerSelector: '#footer',
  8. sidebarTopMargin: 20,
  9. footerThreshold: 40
  10. }, options);
  11. var fixSidebr = function () {
  12. var sidebarSelector = $(this);
  13. var viewportHeight = $(window).height();
  14. var viewportWidth = $(window).width();
  15. var documentHeight = $(document).height();
  16. var headerHeight = $(config.headerSelector).outerHeight();
  17. var navHeight = $(config.navSelector).outerHeight();
  18. var sidebarHeight = sidebarSelector.outerHeight();
  19. var contentHeight = $(config.contentSelector).outerHeight();
  20. var footerHeight = $(config.footerSelector).outerHeight();
  21. var scroll_top = $(window).scrollTop();
  22. var fixPosition = contentHeight - sidebarHeight;
  23. var breakingPoint1 = headerHeight + navHeight + 100;
  24. var breakingPoint2 = documentHeight - (sidebarHeight + footerHeight + config.footerThreshold);
  25. // calculate
  26. if ((contentHeight > sidebarHeight) && (viewportHeight > sidebarHeight)) {
  27. if (scroll_top < breakingPoint1) {
  28. sidebarSelector.removeClass('sticky');
  29. } else if ((scroll_top >= breakingPoint1) && (scroll_top < breakingPoint2)) {
  30. sidebarSelector.addClass('sticky');
  31. } else {
  32. var negative = breakingPoint2 - scroll_top;
  33. sidebarSelector.addClass('sticky');
  34. }
  35. }
  36. };
  37. return this.each(function () {
  38. $(window).on('scroll', $.proxy(fixSidebr, this));
  39. $(window).on('resize', $.proxy(fixSidebr, this))
  40. $.proxy(fixSidebr, this)();
  41. });
  42. };
  43. }(jQuery));