scrollfix

JQuery辅助文本框在浏览器中固定位置,不随浏览器滚动条滚动

目前为 2019-08-20 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/388372/726657/scrollfix.js

  1. // ==UserScript==
  2. // @name scrollfix
  3. // @version 0.0.1
  4. // @namespace tsharp.js
  5. // @description JQuery辅助文本框在浏览器中固定位置,不随浏览器滚动条滚动
  6. // @author jimbo
  7. // @license GPLv3
  8. // @match *
  9. // @icon none
  10. // @require http://code.jquery.com/jquery-3.4.1.min.js
  11. // ==/UserScript==
  12. ; (function ($) {
  13. jQuery.fn.scrollFix = function (height, dir) {
  14. height = height || 0;
  15. height = height == "top" ? 0 : height;
  16. return this.each(function () {
  17. if (height == "bottom") {
  18. height = document.documentElement.clientHeight - this.scrollHeight;
  19. } else if (height < 0) {
  20. height = document.documentElement.clientHeight - this.scrollHeight + height;
  21. }
  22. var that = $(this),
  23. oldHeight = false,
  24. p, r, l = that.offset().left;
  25. dir = dir == "bottom" ? dir : "top"; //默认滚动方向向下
  26. if (window.XMLHttpRequest) { //非ie6用fixed
  27. function getHeight() { //>=0表示上面的滚动高度大于等于目标高度
  28. return (document.documentElement.scrollTop || document.body.scrollTop) + height - that.offset().top;
  29. }
  30. $(window).scroll(function () {
  31. if (oldHeight === false) {
  32. if ((getHeight() >= 0 && dir == "top") || (getHeight() <= 0 && dir == "bottom")) {
  33. oldHeight = that.offset().top - height;
  34. that.css({
  35. position: "fixed",
  36. top: height,
  37. left: l
  38. });
  39. }
  40. } else {
  41. if (dir == "top" && (document.documentElement.scrollTop || document.body.scrollTop) < oldHeight) {
  42. that.css({
  43. position: "fixed"
  44. });
  45. oldHeight = false;
  46. } else if (dir == "bottom" && (document.documentElement.scrollTop || document.body.scrollTop) > oldHeight) {
  47. that.css({
  48. position: "fixed"
  49. });
  50. oldHeight = false;
  51. }
  52. }
  53. });
  54. } else { //for ie6
  55. $(window).scroll(function () {
  56. if (oldHeight === false) { //恢复前只执行一次,减少reflow
  57. if ((getHeight() >= 0 && dir == "top") || (getHeight() <= 0 && dir == "bottom")) {
  58. oldHeight = that.offset().top - height;
  59. r = document.createElement("span");
  60. p = that[0].parentNode;
  61. p.replaceChild(r, that[0]);
  62. document.body.appendChild(that[0]);
  63. that[0].style.position = "absolute";
  64. }
  65. } else if ((dir == "top" && (document.documentElement.scrollTop || document.body.scrollTop) < oldHeight) || (dir == "bottom" && (document.documentElement.scrollTop || document.body.scrollTop) > oldHeight)) { //结束
  66. that[0].style.position = "absolute";
  67. p.replaceChild(that[0], r);
  68. r = null;
  69. oldHeight = false;
  70. } else { //滚动
  71. that.css({
  72. left: l,
  73. top: height + document.documentElement.scrollTop
  74. })
  75. }
  76. });
  77. }
  78. });
  79. };
  80. })(jQuery);