vue实现某元素吸顶或固定位置显示(监听滚动事件)

作者:羞羞的铁拳 时间:2024-05-09 15:15:10 

最近写了一个VUE的web app项目,需要实现某个部位吸顶的效果。即,页面往上滑动,刚好到达该部位时,该部分,固定在顶部显示。

vue实现某元素吸顶或固定位置显示(监听滚动事件)

1、监听滚动事件
利用VUE写一个在控制台打印当前的scrollTop,
首先,在mounted钩子中给window添加一个滚动滚动监听事件,


mounted () {
window.addEventListener('scroll', this.handleScroll)
},

然后在方法中,添加这个handleScroll方法


handleScroll () {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
console.log(scrollTop)
},

控制台打印结果:

vue实现某元素吸顶或固定位置显示(监听滚动事件)

2、监听元素到顶部的距离  并判断滚动的距离如果大于了元素到顶部的距离时,设置searchBar为true,否则就是false


handleScroll () {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
var offsetTop = document.querySelector('#searchBar').offsetTop
if (scrollTop > offsetTop) {
this.searchBarFixed = true
} else {
this.searchBarFixed = false
}
},

先写一个该元素固定到顶部的样式,isFixed(less写法)


.searchBar{
.isFixed{
position:fixed;
background-color:#Fff;
top:0;
z-index:999;
}
ul {
WIDTH:100%;
height: 40px;
line-height: 40px;
display: flex;
li {
font-size: 0.8rem;
text-align: center;
flex: 1;
i {
font-size: 0.9rem;
padding-left: 5px;
color: #ccc;
}
}
border-bottom: 1px solid #ddd;
}
}

然后将需要固定的元素的class与searchBar进行绑定,如果searchBar为true时,就应用这个isFixed样式


<div class="searchBar" id="searchBar">
<ul :class="searchBarFixed == true ? 'isFixed' :''">
<li>区域<i class="iconfont icon-jiantouxia"></i></li>
<li>价格<i class="iconfont icon-jiantouxia"></i></li>
<li>房型<i class="iconfont icon-jiantouxia"></i></li>
<li>更多<i class="iconfont icon-jiantouxia"></i></li>
</ul>
</div>

固定后的结果:

vue实现某元素吸顶或固定位置显示(监听滚动事件)

注意,如果离开该页面需要移除这个监听的事件,不然会报错。


destroyed () {
window.removeEventListener('scroll', this.handleScroll)
},

来源:http://blog.csdn.net/wang1006008051/article/details/78003974

标签:vue,元素吸顶,固定位置,监听滚动
0
投稿

猜你喜欢

  • tensorboard 可以显示graph,却不能显示scalar的解决方式

    2022-07-21 08:55:46
  • Python函数式编程指南(一):函数式编程概述

    2023-07-08 01:20:25
  • python创建文件时去掉非法字符的方法

    2023-10-12 02:15:51
  • golang类型转换组件Cast的使用详解

    2024-05-08 10:22:01
  • Python常用GUI框架原理解析汇总

    2021-05-02 05:13:35
  • Python深入浅出分析enum枚举类

    2022-07-07 15:09:14
  • Git的简单理解及基础操作命令详解

    2023-01-17 11:03:35
  • Python内存泄漏和内存溢出的解决方案

    2022-02-10 11:46:55
  • 简单讲解Python编程中namedtuple类的用法

    2022-05-30 23:32:18
  • MySQL六种约束的示例详解

    2024-01-16 19:15:38
  • sklearn的predict_proba使用说明

    2023-10-24 11:22:08
  • python中list循环语句用法实例

    2022-09-12 15:08:05
  • django 多对多表的创建和插入代码实现

    2021-05-09 03:50:34
  • Python调用Redis的示例代码

    2021-02-10 09:51:10
  • asp如何远程注册DLL

    2010-06-16 09:58:00
  • python内存管理分析

    2022-04-16 22:03:03
  • Python的运算符重载详解

    2022-08-19 21:51:52
  • python3从网络摄像机解析mjpeg http流的示例

    2021-01-12 09:00:54
  • 新兴XML处理方法VTD-XML介绍

    2008-09-04 14:42:00
  • PHP 简单日历实现代码

    2023-07-01 12:00:01
  • asp之家 网络编程 m.aspxhome.com