vue3 吸顶搜索框在页面滚动时改变样式

发布于:2022-08-09 ⋅ 阅读:(423) ⋅ 点赞:(0)

效果图:

在这里插入图片描述
在这里插入图片描述

思路:
监听滚动条距离顶部的距离,在距顶部40px内密集监听(依照自己的情况而定),不断改变样式,实现过度效果

代码:
html

<div id="searchTitle" :style="{ backgroundColor: navbarBg }">
        <div :class="borderBg ? 'inputTitle' : ''" @click="clickChartData(0)">
          <img src="./img/customerIndex/searchTitle.png" alt="">
          <input :class="inputColor ? 'inputtext' : ''" disabled v-model="searchTitle" placeholder="搜索客户姓名">
        </div>
</div>

script

   // 滚动事件
    var navbarBg = ref('rgba(255,255,255,0)')
    var borderBg = ref(false)
    var inputColor = ref(true)
    let IndexTitleScroll = () => {
      // 获取距离顶部的距离
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (scrollTop < 5) {
        navbarBg.value = "rgba(255,255,255,0)";
        borderBg.value = 'url(./img/InputTitle2.png)'
        inputColor.value = true
      } else if (5 < scrollTop && scrollTop < 10) {
        navbarBg.value = "rgba(255,255,255,0.2)";
      } else if (10 < scrollTop && scrollTop < 20) {
        navbarBg.value = "rgba(255,255,255,0.4)";
      } else if (20 < scrollTop && scrollTop < 30) {
        navbarBg.value = "rgba(255,255,255,0.6)";
      } else if (30 < scrollTop && scrollTop < 40) {
        navbarBg.value = "rgba(255,255,255,0.8)";
      } else {
        navbarBg.value = "rgba(255,255,255,1)"
        borderBg.value = true
        inputColor.value = false
      }
    }
    window.addEventListener("scroll", IndexTitleScroll);

style

#searchTitle {
  position: fixed;
  top: 0;
  left: 50%;
  z-index: 9999;
  width: 100%;
  max-width: 375px;
  transform: translateX(-50%);
  padding: 20px 0px 15px;

  div {
    display: flex;
    align-items: center;
    width: 90%;
    padding: 6px 0px;
    margin: 0px auto;
    background-image: url(./img/InputTitle2.png);
    background-size: 100% 100%;
  }

  div.inputTitle {
    background-image: url(./img/InputTitle.png);
  }

  div img {
    width: 14px;
    margin: 0px 10px 0px 15px;
  }

  div input {
    flex: 1;
    height: 96%;
    border: none;
    background: none;
  }
  
  // 改变文本框内提示语句的文字样式
  div input.inputtext::-webkit-input-placeholder {
    /* Chrome/Opera/Safari */
    color: #fff;
  }

  div input.inputtext:-ms-input-placeholder {
    /* IE 10+ */
    color: #fff;
  }

  div input.inputtext:-moz-placeholder {
    /* Firefox 18- */
    color: #fff;
  }

  div input.inputtext::-moz-placeholder {
    /* Firefox 19+ */
    color: #fff;
  }
}
本文含有隐藏内容,请 开通VIP 后查看