当用户滚动经过一个元素时,我试图修复它,但我有一个问题。由于某些原因,我的元素(在我的例子中是一个导航栏)总是返回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复制