su-sticky.vue 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <template>
  2. <view class="u-sticky" :id="elId" :style="[style]">
  3. <view :style="[stickyContent]" class="u-sticky__content"><slot /></view>
  4. </view>
  5. </template>
  6. <script>
  7. import { deepMerge, addStyle, addUnit, guid, getPx, os } from '@/common/helper';
  8. import sheep from '@/common';
  9. /**
  10. * sticky 吸顶
  11. * @description 该组件与CSS中position: sticky属性实现的效果一致,当组件达到预设的到顶部距离时, 就会固定在指定位置,组件位置大于预设的顶部距离时,会重新按照正常的布局排列。
  12. * @property {String | Number} offsetTop 吸顶时与顶部的距离,单位px(默认 0 )
  13. * @property {String | Number} customNavHeight 自定义导航栏的高度 (h5 默认44 其他默认 0 )
  14. * @property {Boolean} stickyToTop 是否开启吸顶功能 (默认 false )
  15. * @property {String} bgColor 组件背景颜色(默认 '#ffffff' )
  16. * @property {String | Number} zIndex 吸顶时的z-index值
  17. * @property {String | Number} index 自定义标识,用于区分是哪一个组件
  18. * @property {Object} customStyle 组件的样式,对象形式
  19. * @event {Function} fixed 组件吸顶时触发
  20. * @event {Function} unfixed 组件取消吸顶时触发
  21. * @example <u-sticky offsetTop="200"><view>塞下秋来风景异,衡阳雁去无留意</view></u-sticky>
  22. */
  23. export default {
  24. name: 'su-sticky',
  25. props: {
  26. // 吸顶容器到顶部某个距离的时候,进行吸顶,在H5平台,NavigationBar为44px
  27. offsetTop: {
  28. type: [String, Number],
  29. default: 0,
  30. },
  31. // 自定义导航栏的高度
  32. customNavHeight: {
  33. type: [String, Number],
  34. // #ifdef H5
  35. // H5端的导航栏属于“自定义”导航栏的范畴,因为它是非原生的,与普通元素一致
  36. default: sheep.$platform.navbar-sheep.$platform.device.statusBarHeight,
  37. // #endif
  38. // #ifndef H5
  39. default: sheep.$platform.navbar,
  40. // #endif
  41. },
  42. // 是否开启吸顶功能
  43. stickyToTop: {
  44. type: Boolean,
  45. default: false,
  46. },
  47. // 吸顶区域的背景颜色
  48. bgColor: {
  49. type: String,
  50. default: 'transparent',
  51. },
  52. // z-index值
  53. zIndex: {
  54. type: [String, Number],
  55. default: '',
  56. },
  57. // 列表中的索引值
  58. index: {
  59. type: [String, Number],
  60. default: '',
  61. },
  62. customStyle: {
  63. type: [Object, String],
  64. default: () => ({}),
  65. },
  66. },
  67. data() {
  68. return {
  69. cssSticky: false, // 是否使用css的sticky实现
  70. stickyTop: 0, // 吸顶的top值,因为可能受自定义导航栏影响,最终的吸顶值非offsetTop值
  71. elId: guid(),
  72. left: 0, // js模式时,吸顶的内容因为处于postition: fixed模式,为了和原来保持一致的样式,需要记录并重新设置它的left,height,width属性
  73. width: 'auto',
  74. height: 'auto',
  75. fixed: false, // js模式时,是否处于吸顶模式
  76. };
  77. },
  78. computed: {
  79. style() {
  80. const style = {};
  81. if (!this.stickyToTop) {
  82. if (this.cssSticky) {
  83. style.position = 'sticky'
  84. style.zIndex = this.uZindex
  85. style.top = addUnit(this.stickyTop)
  86. } else {
  87. style.height = this.fixed ? this.height + 'px' : 'auto'
  88. }
  89. } else {
  90. // 无需吸顶时,设置会默认的relative(nvue)和非nvue的static静态模式即可
  91. // #ifdef APP-NVUE
  92. style.position = 'relative'
  93. // #endif
  94. // #ifndef APP-NVUE
  95. style.position = 'static'
  96. // #endif
  97. }
  98. style.backgroundColor = this.bgColor
  99. return deepMerge(addStyle(this.customStyle), style)
  100. },
  101. // 吸顶内容的样式
  102. stickyContent() {
  103. const style = {};
  104. if (!this.cssSticky) {
  105. style.position = this.fixed ? 'fixed' : 'static';
  106. style.top = this.stickyTop + 'px';
  107. style.left = this.left + 'px';
  108. style.width = this.width == 'auto' ? 'auto' : this.width + 'px';
  109. style.zIndex = this.uZindex;
  110. style.backgroundColor = this.fixed ? '#FFFFFF' : this.bgColor
  111. }
  112. return style;
  113. },
  114. uZindex() {
  115. return this.zIndex ? this.zIndex : 970;
  116. },
  117. },
  118. mounted() {
  119. this.init();
  120. },
  121. methods: {
  122. init() {
  123. this.getStickyTop();
  124. // 判断使用的模式
  125. this.checkSupportCssSticky();
  126. // 如果不支持css sticky,则使用js方案,此方案性能比不上css方案
  127. if (!this.cssSticky) {
  128. !this.stickyToTop && this.initObserveContent();
  129. }
  130. },
  131. $uGetRect(selector, all) {
  132. return new Promise((resolve) => {
  133. uni
  134. .createSelectorQuery()
  135. .in(this)
  136. [all ? 'selectAll' : 'select'](selector)
  137. .boundingClientRect((rect) => {
  138. if (all && Array.isArray(rect) && rect.length) {
  139. resolve(rect);
  140. }
  141. if (!all && rect) {
  142. resolve(rect);
  143. }
  144. })
  145. .exec();
  146. });
  147. },
  148. initObserveContent() {
  149. // 获取吸顶内容的高度,用于在js吸顶模式时,给父元素一个填充高度,防止"塌陷"
  150. this.$uGetRect('#' + this.elId).then((res) => {
  151. this.height = res.height;
  152. this.left = res.left;
  153. this.width = res.width;
  154. this.$nextTick(() => {
  155. this.observeContent();
  156. });
  157. });
  158. },
  159. observeContent() {
  160. // 先断掉之前的观察
  161. this.disconnectObserver('contentObserver');
  162. const contentObserver = uni.createIntersectionObserver({
  163. // 检测的区间范围
  164. thresholds: [0.95, 0.98, 1],
  165. });
  166. // 到屏幕顶部的高度时触发
  167. contentObserver.relativeToViewport({
  168. top: -this.stickyTop,
  169. });
  170. // 绑定观察的元素
  171. contentObserver.observe(`#${this.elId}`, (res) => {
  172. this.setFixed(res.boundingClientRect.top);
  173. });
  174. this.contentObserver = contentObserver;
  175. },
  176. setFixed(top) {
  177. // 判断是否出于吸顶条件范围
  178. const fixed = top < this.stickyTop;
  179. this.fixed = fixed;
  180. },
  181. disconnectObserver(observerName) {
  182. // 断掉观察,释放资源
  183. const observer = this[observerName];
  184. observer && observer.disconnect();
  185. },
  186. getStickyTop() {
  187. this.stickyTop = getPx(this.offsetTop) + getPx(this.customNavHeight);
  188. },
  189. async checkSupportCssSticky() {
  190. // #ifdef H5
  191. // H5,一般都是现代浏览器,是支持css sticky的,这里使用创建元素嗅探的形式判断
  192. if (this.checkCssStickyForH5()) {
  193. this.cssSticky = false;
  194. }
  195. // #endif
  196. // 如果安卓版本高于8.0,依然认为是支持css sticky的(因为安卓7在某些机型,可能不支持sticky)
  197. if (os() === 'android' && Number(uni.getDeviceInfo().system) > 8) {
  198. this.cssSticky = false;
  199. }
  200. // APP-Vue和微信平台,通过computedStyle判断是否支持css sticky
  201. // #ifdef APP-VUE || MP-WEIXIN
  202. this.cssSticky = await this.checkComputedStyle();
  203. // #endif
  204. // ios上,从ios6开始,都是支持css sticky的
  205. if (os() === 'ios') {
  206. this.cssSticky = false;
  207. }
  208. // nvue,是支持css sticky的
  209. // #ifdef APP-NVUE
  210. this.cssSticky = false;
  211. // #endif
  212. },
  213. // 在APP和微信小程序上,通过uni.createSelectorQuery可以判断是否支持css sticky
  214. checkComputedStyle() {
  215. // 方法内进行判断,避免在其他平台生成无用代码
  216. // #ifdef APP-VUE || MP-WEIXIN
  217. return new Promise((resolve) => {
  218. uni
  219. .createSelectorQuery()
  220. .in(this)
  221. .select('.u-sticky')
  222. .fields({
  223. computedStyle: ['position'],
  224. })
  225. .exec((e) => {
  226. resolve('sticky' === e[0].position);
  227. });
  228. });
  229. // #endif
  230. },
  231. // H5通过创建元素的形式嗅探是否支持css sticky
  232. // 判断浏览器是否支持sticky属性
  233. checkCssStickyForH5() {
  234. // 方法内进行判断,避免在其他平台生成无用代码
  235. // #ifdef H5
  236. const vendorList = ['', '-webkit-', '-ms-', '-moz-', '-o-'],
  237. vendorListLength = vendorList.length,
  238. stickyElement = document.createElement('div');
  239. for (let i = 0; i < vendorListLength; i++) {
  240. stickyElement.style.position = vendorList[i] + 'sticky';
  241. if (stickyElement.style.position !== '') {
  242. return true;
  243. }
  244. }
  245. return false;
  246. // #endif
  247. },
  248. },
  249. beforeDestroy() {
  250. this.disconnectObserver('contentObserver');
  251. },
  252. };
  253. </script>
  254. <style lang="scss" scoped>
  255. .u-sticky {
  256. /* #ifdef APP-VUE || MP-WEIXIN */
  257. // 此处默认写sticky属性,是为了给微信和APP通过uni.createSelectorQuery查询是否支持css sticky使用
  258. position: sticky;
  259. /* #endif */
  260. }
  261. </style>