0
点赞
收藏
分享

微信扫一扫

vue 页面向下滚动到指定位置时,顶部显示悬浮搜索框


目录

​​核心代码​​

​​添加对页面滚动事件的监听​​

​​ 当页面滚动到指定位置时,显示搜索框​​

​​悬浮搜索框的样式 fixed​​

​​完整演示代码​​

 

效果可参考天猫首页 ​​https://www.tmall.com/​​

vue 页面向下滚动到指定位置时,顶部显示悬浮搜索框_指定位置

核心代码

添加对页面滚动事件的监听

mounted() {
// 监听页面滚动事件
window.addEventListener("scroll", this.showSearch)
},

 当页面滚动到指定位置时,显示搜索框

showSearch() {
// 获取当前滚动条向下滚动的距离
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 当页面滚动到高度300px处时,显示搜索框
if (scrollTop > 300) {
this.showFixedSearch = true;
} else {
this.showFixedSearch = false;
}
},

悬浮搜索框的样式 fixed

.fixedSearch {
position: fixed;
width: 100%;
z-index: 999;
background: #f6f6f6;
height: 120px;
overflow: hidden;
}

完整演示代码

为了使悬浮搜索框的显示和隐藏过渡更自然,范例中使用了animate的动画效果,vue安装配置使用animate的方法详见博客

<template>
<div>
<transition
enter-active-class="animate__animated animate__fadeIn"
leave-active-class="animate__animated animate__fadeOut"
>
<div class="fixedSearch" v-show="showFixedSearch">
<img class="searchBox"
src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1022330132,1035223511&fm=26&gp=0.jpg"
alt="搜索框图片">
</div>
</transition>
<div class="box100">0</div>
<div class="box100">100</div>
<div class="box100">200</div>
<div class="box100">300</div>
<div class="box100">400</div>
<div class="box100">500</div>
<div class="box100">600</div>
<div class="box100">700</div>
<div class="box100">800</div>
<div class="box100">900</div>
<div class="box100">1000</div>
</div>
</template>
<script>
export default {
data() {
return {
showFixedSearch: false
}
},
mounted() {
// 监听页面滚动事件
window.addEventListener("scroll", this.showSearch)
},
methods: {
showSearch() {
// 获取当前滚动条向下滚动的距离
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 当页面滚动到高度300px处时,显示搜索框
if (scrollTop > 300) {
this.showFixedSearch = true;
} else {
this.showFixedSearch = false;
}
},
}
}
</script>
<style scoped>
.fixedSearch {
position: fixed;
width: 100%;
z-index: 999;
background: #f6f6f6;
height: 120px;
overflow: hidden;
}

.searchBox {
position: absolute;
top: -100px;
left: 50%;
transform: translateX(-50%);
}

.box100 {
height: 100px;
background: #3a8ee6;
border: 1px solid black;
}
</style>

 

举报

相关推荐

0 条评论