scrollFix.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. ;(function($) {
  2. jQuery.fn.scrollFix = function(height, dir) {
  3. height = height || 0;
  4. height = height == "top" ? 0 : height;
  5. return this.each(function() {
  6. if (height == "bottom") {
  7. height = document.documentElement.clientHeight - this.scrollHeight;
  8. } else if (height < 0) {
  9. height = document.documentElement.clientHeight - this.scrollHeight + height;
  10. }
  11. var that = $(this),
  12. oldHeight = false,
  13. p, r, l = that.offset().left;
  14. dir = dir == "bottom" ? dir : "top"; //默认滚动方向向下
  15. if (window.XMLHttpRequest) { //非ie6用fixed
  16. function getHeight() { //>=0表示上面的滚动高度大于等于目标高度
  17. return (document.documentElement.scrollTop || document.body.scrollTop) + height - that.offset().top;
  18. }
  19. $(window).scroll(function() {
  20. if (oldHeight === false) {
  21. if ((getHeight() >= 0 && dir == "top") || (getHeight() <= 0 && dir == "bottom")) {
  22. oldHeight = that.offset().top - height;
  23. that.css({
  24. position: "fixed",
  25. top: height,
  26. left: l
  27. });
  28. }
  29. } else {
  30. if (dir == "top" && (document.documentElement.scrollTop || document.body.scrollTop) < oldHeight) {
  31. that.css({
  32. position: "static"
  33. });
  34. oldHeight = false;
  35. } else if (dir == "bottom" && (document.documentElement.scrollTop || document.body.scrollTop) > oldHeight) {
  36. that.css({
  37. position: "static"
  38. });
  39. oldHeight = false;
  40. }
  41. }
  42. });
  43. } else { //for ie6
  44. $(window).scroll(function() {
  45. if (oldHeight === false) { //恢复前只执行一次,减少reflow
  46. if ((getHeight() >= 0 && dir == "top") || (getHeight() <= 0 && dir == "bottom")) {
  47. oldHeight = that.offset().top - height;
  48. r = document.createElement("span");
  49. p = that[0].parentNode;
  50. p.replaceChild(r, that[0]);
  51. document.body.appendChild(that[0]);
  52. that[0].style.position = "absolute";
  53. }
  54. } else if ((dir == "top" && (document.documentElement.scrollTop || document.body.scrollTop) < oldHeight) || (dir == "bottom" && (document.documentElement.scrollTop || document.body.scrollTop) > oldHeight)) { //结束
  55. that[0].style.position = "static";
  56. p.replaceChild(that[0], r);
  57. r = null;
  58. oldHeight = false;
  59. } else { //滚动
  60. that.css({
  61. left: l,
  62. top: height + document.documentElement.scrollTop
  63. })
  64. }
  65. });
  66. }
  67. });
  68. };
  69. })(jQuery);