create-intersection-observer.uvue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <template>
  2. <view>
  3. <page-head :title="title"></page-head>
  4. <view class="uni-padding-wrap uni-common-mt">
  5. <view class="uni-title uni-common-mt">
  6. {{appear ? '小球出现' : '小球消失'}}
  7. </view>
  8. <scroll-view class="scroll-view" scroll-y :scrollTop="scrollTop">
  9. <view class="scroll-area">
  10. <text class="notice">向下滚动让小球出现</text>
  11. <view class="ball"></view>
  12. </view>
  13. </scroll-view>
  14. </view>
  15. </view>
  16. </template>
  17. <script lang="uts">
  18. let observer: IntersectionObserver | null = null;
  19. export default {
  20. data() {
  21. return {
  22. appear: false,
  23. title:'intersectionObserver',
  24. // 自动化测试
  25. testRes: null as ObserveResult | null,
  26. scrollTop:0
  27. }
  28. },
  29. onReady() {
  30. observer = uni.createIntersectionObserver(this,{});
  31. observer.relativeTo('.scroll-view').observe('.ball', (res:ObserveResult) => {
  32. this.testRes = res;
  33. if (res.intersectionRatio > 0 && !this.appear) {
  34. this.appear = true;
  35. } else if (res.intersectionRatio <= 0 && this.appear) {
  36. this.appear = false;
  37. }
  38. })
  39. },
  40. onUnload() {
  41. if (observer) {
  42. observer.disconnect()
  43. }
  44. }
  45. }
  46. </script>
  47. <style>
  48. .scroll-view {
  49. height: 200px;
  50. background: #fff;
  51. border: 1px solid #ccc;
  52. box-sizing: border-box;
  53. }
  54. .scroll-area {
  55. height: 650px;
  56. display: flex;
  57. flex-direction: column;
  58. align-items: center;
  59. }
  60. .notice {
  61. margin-top: 75px;
  62. margin:75px 0 200px 0;
  63. }
  64. .ball {
  65. width: 100px;
  66. height: 100px;
  67. background: #4cd964;
  68. border-radius: 100px;
  69. }
  70. </style>