fe-drone-ci/src/components/Sticky/index.vue

85 lines
1.8 KiB
Vue
Raw Normal View History

2017-04-18 07:09:13 +00:00
<template>
2017-07-06 09:56:17 +00:00
<div :style="{height:height+'px',zIndex:zIndex}">
<div :class="className" :style="{top:stickyTop+'px',zIndex:zIndex,position:position,width:width,height:height+'px'}">
<slot>
<div>sticky</div>
</slot>
2017-04-18 07:09:13 +00:00
</div>
2017-07-06 09:56:17 +00:00
</div>
2017-04-18 07:09:13 +00:00
</template>
2017-07-06 09:56:17 +00:00
2017-04-18 07:09:13 +00:00
<script>
2017-08-22 07:43:34 +00:00
export default {
name: 'Sticky',
props: {
stickyTop: {
type: Number,
default: 0
2017-07-06 09:56:17 +00:00
},
2017-08-22 07:43:34 +00:00
zIndex: {
type: Number,
default: 1
2017-07-06 09:56:17 +00:00
},
2017-08-22 07:43:34 +00:00
className: {
type: String,
default: ''
2017-08-22 07:43:34 +00:00
}
},
data() {
return {
active: false,
position: '',
width: undefined,
2018-05-31 05:22:12 +00:00
height: undefined,
isSticky: false
2017-08-22 07:43:34 +00:00
}
},
mounted() {
this.height = this.$el.getBoundingClientRect().height
window.addEventListener('scroll', this.handleScroll)
2018-05-31 02:49:11 +00:00
window.addEventListener('resize', this.handleReize)
},
activated() {
this.handleScroll()
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
2018-05-31 02:49:11 +00:00
window.removeEventListener('resize', this.handleReize)
},
2017-08-22 07:43:34 +00:00
methods: {
sticky() {
if (this.active) {
return
2017-04-18 07:09:13 +00:00
}
2017-08-22 07:43:34 +00:00
this.position = 'fixed'
this.active = true
this.width = this.width + 'px'
2018-05-31 05:22:12 +00:00
this.isSticky = true
2017-07-06 09:56:17 +00:00
},
2017-08-22 07:43:34 +00:00
reset() {
if (!this.active) {
return
}
this.position = ''
this.width = 'auto'
this.active = false
2018-05-31 05:22:12 +00:00
this.isSticky = false
2017-07-06 09:56:17 +00:00
},
2017-08-22 07:43:34 +00:00
handleScroll() {
this.width = this.$el.getBoundingClientRect().width
const offsetTop = this.$el.getBoundingClientRect().top
2018-05-31 09:16:24 +00:00
if (offsetTop < this.stickyTop) {
2017-08-22 07:43:34 +00:00
this.sticky()
return
}
this.reset()
2018-05-31 02:49:11 +00:00
},
handleReize() {
2018-05-31 05:22:12 +00:00
if (this.isSticky) {
this.width = this.$el.getBoundingClientRect().width + 'px'
}
2017-07-06 09:56:17 +00:00
}
2017-08-22 07:43:34 +00:00
}
}
2017-04-18 07:09:13 +00:00
</script>