intersection-observer.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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>
  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>
  18. let observer = null;
  19. export default {
  20. data() {
  21. return {
  22. appear: false,
  23. title:'intersectionObserver'
  24. }
  25. },
  26. onReady() {
  27. observer = uni.createIntersectionObserver(this);
  28. observer.relativeTo('.scroll-view').observe('.ball', (res) => {
  29. if (res.intersectionRatio > 0 && !this.appear) {
  30. this.appear = true;
  31. } else if (!res.intersectionRatio > 0 && this.appear) {
  32. this.appear = false;
  33. }
  34. })
  35. },
  36. onUnload() {
  37. if (observer) {
  38. observer.disconnect()
  39. }
  40. }
  41. }
  42. </script>
  43. <style>
  44. .scroll-view {
  45. height: 400rpx;
  46. background: #fff;
  47. border: 1px solid #ccc;
  48. box-sizing: border-box;
  49. }
  50. .scroll-area {
  51. height: 1300rpx;
  52. display: flex;
  53. flex-direction: column;
  54. align-items: center;
  55. }
  56. .notice {
  57. margin-top: 150rpx;
  58. margin: 150rpx 0 400rpx 0;
  59. }
  60. .ball {
  61. width: 200rpx;
  62. height: 200rpx;
  63. background: #4cd964;
  64. border-radius: 50%;
  65. }
  66. </style>