当用户滚动经过一个元素时,我试图修复它,但我有一个问题。由于某些原因,我的元素(在我的例子中是一个导航栏)总是返回0,尽管高度大约是300px。
这是我挂载的方法,我在其中进行计算,正如您所看到的,我在控制台记录stickyTop,始终为0。
我尝试使用offsetTop和getBoundingClientRect().top,它们都总是返回0。
代码语言:javascript复制mounted() {
console.log(this.$options.name+' component successfully mounted');
let self = this;
let sticky = document.getElementById("sticky");
//sticky.style.border = '10px solid red';
//let stickyTop = sticky.getBoundingClientRect().top;
let stickyTop = sticky.offsetTop;
console.log(stickyTop);
let scrolled = false;
let $window = window;
window.addEventListener('scroll', function(e) {
scrolled = true;
});
let timeout = setInterval(function() {
/* If the page was scrolled, handle the scroll */
if (scrolled) {
scrolled = false;
if (window.pageYOffset > stickyTop) {
self.isScrolled = true;
}
else {
self.isScrolled = false;
}
}
}, 2000);
},我的完整组件以防万一:
代码语言:javascript复制
import $ from 'jquery';
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';
export default {
name: 'LAYOUTnav6',
computed: {
...mapState('Cart', ['cartItems']),
withLinks: function(){
return this.globals.navLinks.filter(link => link.sublinks.length > 0 && link.subLinks);
},
visibleLinks: function(){
return this.globals.navLinks.filter(link => link.isVisible && !link.hasSublinks || link.isVisible && link.hasSublinks && link.sublinks.length > 0);
}
},
data: function () {
return {
activeNav: null,
showResponsiveNav: false,
isScrolled: false,
}
},
props: {
globals: {required:true},
meta: {required:true}
},
mounted() {
console.log(this.$options.name+' component successfully mounted');
let self = this;
let sticky = document.getElementById("sticky");
//sticky.style.border = '10px solid red';
//let stickyTop = sticky.getBoundingClientRect().top;
let stickyTop = sticky.offsetTop;
console.log(stickyTop);
let scrolled = false;
let $window = window;
window.addEventListener('scroll', function(e) {
scrolled = true;
});
let timeout = setInterval(function() {
/* If the page was scrolled, handle the scroll */
if (scrolled) {
scrolled = false;
if (window.pageYOffset > stickyTop) {
self.isScrolled = true;
}
else {
self.isScrolled = false;
}
}
}, 2000);
},
methods: {
...mapMutations('Cart', ['TOGGLE_CART_TAB']),
selectNav: function(link, event){
if(link.sublinks.length > 0){
//event.preventDefault();
this.activeNav = link.name;
}
else{
this.activeNav = link.name;
this.showResponsiveNav = !this.showResponsiveNav
}
},
}
};