vue组件化
原理:检查是否兼容position: sticky ,若兼容就使用,若不兼容则在watch监听高度(若高度是变化的)或者在mounted中直接调用(高度不变)
<template>
<div class="header_sticky">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'stickyHeader',
computed: {
randomId: function(){
return 'randomId_' + Number(Math.random().toString().substr(3,3) + Date.now()).toString(36);
},
targetElement_: function() {
return this.$el
}
},
methods: {
// css: 用于替换的css样式; (一般用默认的)
sticky_(css='sticky_') {
if (CSS.supports('position', 'sticky') || CSS.supports('position', '-webkit-sticky')) {
console.log('>>>>>>>>> sticky is supported')
} else {
let newNodeTop;
let header = this.targetElement_;
if(document.getElementById(this.randomId)) {
newNodeTop = document.getElementById(this.randomId);
}else{
newNodeTop = document.createElement("div");
newNodeTop.id = this.randomId;
header.parentNode.insertBefore(newNodeTop, header);
header.classList.add(css);
}
setTimeout(() => {
let height = header.offsetHeight + 1; //高度 + 1 以防有小数点
newNodeTop.style.height = height + 'px';
}, 0)
}
},
}
}
</script>
注意:要用异步获取高度
css
.header_sticky {
width: 100%;
position: sticky;
position: -webkit-sticky;
top: 0;
z-index: 100;
transition: height 1s;
-moz-transition: height 1s;
-webkit-transition: height 1s;
-o-transition: height 1s;
}
.sticky_ {
width: 100%;
position: fixed;
position: -webkit-fixed;
top: 0;
z-index: 100;
}
在watch中监听高度变化
watch: {
oldToNew(newVal, oldVal) {
if(newVal.length !== oldVal.length) {
this.$refs.sticky_.sticky_()
}
}
}
在mounted中获取高度变化
this.$refs.sticky_.sticky_()
<使用>
html
<sticky-header ref="sticky_">
<!-- contents -->
</sticky-header>