-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsticky.vue
More file actions
99 lines (96 loc) · 3.29 KB
/
sticky.vue
File metadata and controls
99 lines (96 loc) · 3.29 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<template>
<div class="sticky" :style="getPosition">
<div class="sticky-warp">
<slot></slot>
</div>
</div>
</template>
<script type="text/babel">
export default {
data () {
return {}
},
computed: {
getPosition(){
var position = this.cssSupport('position', 'sticky') ? 'sticky' : 'relative';
return 'position:' + position;
}
},
props: {},
beforeMount () {
},
mounted(){
this.init();
},
deactivated(){
if(this.cssSupport('position', 'sticky')) {
return;
}
/*复位*/
var elWarp = this.$el.querySelector('.sticky-warp');
elWarp.position = 'absolute';
},
methods: {
init(){
if (this.cssSupport('position', 'sticky')) {
return;
}
var el = this.$el,
elWarp = this.$el.querySelector('.sticky-warp'),
target = this.getScrollEventTarget(el),
top = this.getNumberValue(document.defaultView.getComputedStyle(el).top),
height = this.getNumberValue(document.defaultView.getComputedStyle(el).height);
this.addScrollListen(target, ()=> {
if (el.getBoundingClientRect().top <= top) {
elWarp.style.position = 'fixed';
}
if (target.scrollTop <= height && elWarp.style.position != 'absolute') {
elWarp.style.position = 'absolute';
}
})
},
getNumberValue(pxValue){
var value = String(pxValue).match(/^[0-9]+/g);
return value ? Number(value) : undefined;
},
addScrollListen(target, cb){
target.addEventListener('scroll', ()=> {
cb && cb();
});
},
getScrollEventTarget: function (element) {
let currentNode = element;
while (currentNode && currentNode.tagName !== 'HTML' &&
currentNode.tagName !== 'BODY' && currentNode.nodeType === 1) {
let overflowY = document.defaultView.getComputedStyle(currentNode).overflowY;
if (overflowY === 'scroll' || overflowY === 'auto') {
return currentNode;
}
currentNode = currentNode.parentNode;
}
return window;
},
cssSupport: function (attr, value) {
var element = document.createElement('div');
if (attr in element.style) {
element.style[attr] = value;
return element.style[attr] === value;
} else {
return false;
}
}
},
}
</script>
<style scoped lang="less" rel="stylesheet/less">
.sticky {
width: 100%;
.sticky-warp {
width: 100%;
background: inherit;
will-change: change;
height: inherit;
top: inherit;
}
}
</style>