vue可以使用position:fixed实现页面中部分区域一直浮动显示在页面的可视区域中
position:fixed可以实现页面浮动显示
# 实现
# 在style中添加position:fixed
<el-card :body-style="{ 'padding': '0px', 'line-height': '36px'}" style="margin-top:20px;position:fixed;width:330px;bottom:120px">
</el-card>
1
2
2
上面是我使用时的代码,position:fixed可以设置left,right,top,bottom四个值分别是距离显示区域左右上下的偏移量,因为我在使用时只需要保证浮动显示部分不在页面最底端,所以我只设置了bottom。
# 配合监听页面滚动
但是使用时发现,浮动部分会一直显示在页面右下角,当初次打开页面或者滚动到页面顶部时,会遮挡初始页面右下角部分内容,所以进行优化,当页面滚动到某一位置是再进行浮动显示,在到达该位置之前,浮动显示区域显示在页面某个固定区域,而不是浮动显示。
# 首先将需要浮动部分style设置为动态可变style
<el-card :body-style="{ 'padding': '0px', 'line-height': '36px'}" :style="this.style">
</el-card>
1
2
2
# 在data中定义该style变量,并设置默认值为固定位置显示
<script>
export default {
data() {
return {
style: 'margin-top:20px;'
}
}
}
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 使用监听页面滚动方法
监听页面滚动方法具体可见我的这篇文章:vue监听页面滚动
<script>
export default {
data() {
return {
style: 'margin-top:20px;'
}
},
mounted() {
window.addEventListener('scroll', this.getScroll);
},
destroyed(){
window.removeEventListener('scroll', this.getScroll);
},
methods: {
//监听滚动
getScroll(){
this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
if (!!document.documentElement.scrollTop &&document.documentElement.scrollTop >= 605){
this.style = 'margin-top:20px;position:fixed;width:330px;bottom:120px'
} else {
this.style = 'margin-top:20px;'
}
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 兼容问题
调试时发现显示正常,到达某一位置能够较为平滑的进行浮动显示,但是当我全屏时发现,由于页面可视区域变高,设置的滚动高度为605时浮动有较强的顿挫感,视觉冲击较大,不平滑,不美观,需要对此问题进行解决。
# 通过获取网页可见区域高clientHeight实现兼容
获取网页可见区域高clientHeight,用网页长度减掉clientHeight即为开始实现浮动显示的高度。
<script>
export default {
data() {
return {
style: 'margin-top:20px;'
}
},
mounted() {
window.addEventListener('scroll', this.getScroll);
},
destroyed(){
window.removeEventListener('scroll', this.getScroll);
},
methods: {
//监听滚动
getScroll(){
this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
if (!!document.documentElement.scrollTop &&document.documentElement.scrollTop >= (1245 - document.documentElement.clientHeight)){
this.style = 'margin-top:20px;position:fixed;width:330px;bottom:120px'
} else {
this.style = 'margin-top:20px;'
}
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26