<template>
  <view class='container'>
    <view class='navbar' :style='navbarStyle'>
      <view class='back-btn'>返回</view>
      <view class='search-box' :style='searchBoxStyle'>
        <input v-model='keyword' type='text' placeholder='搜索'/>
      </view>
    </view>
    <view class='content' @scroll='onPageScroll'>
      <!-- 页面内容 -->
    </view>
  </view>
</template>
<script>
  export default {
    data() {
      return {
        navbarStyle: {}, // 导航栏样式
        searchBoxStyle: {}, // 搜索框样式
        keyword: '', // 搜索关键字
        originalNavbarHeight: 64, // 原始导航栏高度
        scrollThreshold: 200 // 滚动阈值
      };
    },
    methods: {
      onPageScroll(e) {
        if (e.scrollTop > this.scrollThreshold) {
          // 滚动超过阈值时,搜索框移动到导航栏
          const distance = e.scrollTop - this.scrollThreshold;
          this.navbarStyle = {
            transform: `translateY(-${distance}px)`,
            height: `${this.originalNavbarHeight + distance}px`
          };
          this.searchBoxStyle = {
            width: `${this.originalNavbarHeight - distance}px`,
            transform: `translateY(-${distance}px)`
          };
        } else {
          this.navbarStyle = {};
          this.searchBoxStyle = {};
        }
      }
    }
  };
</script>
<style>
  .container {
    height: 100vh;
    overflow-y: scroll;
  }

  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: {{originalNavbarHeight}}px;
    background-color: #333;
    color: #fff;
    display: flex;
    align-items: center;
    z-index: 999;
    transition: all 0.3s;
  }

  .back-btn {
    margin-left: 10px;
  }

  .search-box {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 10px;
    transition: all 0.3s;
  }

  .search-box input {
    height: 30px;
    border-radius: 15px;
    padding: 0 10px;
    background-color: #fff;
    color: #333;
    border: none;
    outline: none;
    transition: all 0.3s;
  }

  .content {
    margin-top: {{originalNavbarHeight}}px;
    /* 其他样式 */
  }
</style>
<p>在以上示例中,<code>onPageScroll</code>方法监听了页面滚动事件,在滚动超过阈值时,根据滚动距离来实现导航栏和搜索框的动画效果。通过设置<code>transform</code>属性来实现元素的位移,通过设置<code>height</code>和<code>width</code>属性来实现元素的缩放。</p>

原文地址: https://www.cveoy.top/t/topic/p8JR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录